Merge upstream main

# Conflicts:
#	docs/control-protocol.md
This commit is contained in:
Cristi Radu committed 2026-11-09 19:34:53 +02:00
commit 1be423b30e
401 files changed
+30185 -2599

No files matched your search

+2 -1
View File
@@ -42,7 +42,7 @@ next to them.
| `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) |
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg` (115 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg` (116 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
@@ -58,6 +58,7 @@ next to them.
| `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/clip-below.svg`, `assets/icons/clip-release.svg` | Clipping-mask cursors (⌥ over the line between two layers): a hooked arrow onto the layer below; the same with a small "no" badge to release | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/layer-mask.svg`, `assets/icons/adjustment-layer.svg` | Layers panel footer glyphs: Add a mask (a frame around a solid disc) and New Fill or Adjustment Layer (a circle, one half solid), drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/vertical-align-{top,middle,bottom}.svg` | Type options-bar alignment glyphs for vertical text: three columns hanging from a top line, centred on a middle line, or standing on a bottom line, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/align-edge-*.svg`, `assets/icons/distribute-*.svg` | Move tool options-bar glyphs: Align (six edges/centres) and Distribute (edges, centres, spacing), a guide line or edge lines with bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/ellipse-dashed.svg` | Elliptical Marquee tool glyph: a dashed horizontal ellipse, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/frame-placeholder.svg` | Frame tool glyph: an empty placeholder frame, crossed corner to corner | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
Generated
+16 -28
View File
@@ -1406,17 +1406,17 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1439,7 +1439,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"thiserror 2.0.21",
]
@@ -1457,7 +1457,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"bytemuck",
"hayro",
@@ -1469,7 +1469,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"craft-winprint-gdi",
"log",
@@ -1483,7 +1483,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1504,7 +1504,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"chrono",
"dunce",
@@ -1530,7 +1530,7 @@ dependencies = [
[[package]]
name = "craft-winprint-gdi"
version = "0.1.0"
source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312"
source = "git+https://github.com/storytold/winprint.rs?rev=64e7afd4d1483512385012c340ecaaaf0f3beb7f#64e7afd4d1483512385012c340ecaaaf0f3beb7f"
dependencies = [
"windows-sys 0.61.2",
]
@@ -2964,7 +2964,7 @@ dependencies = [
[[package]]
name = "hayro"
version = "0.7.1"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"bytemuck",
"hayro-interpret",
@@ -2994,7 +2994,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3012,7 +3012,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3036,7 +3036,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -5618,6 +5618,7 @@ dependencies = [
"crc32fast",
"flate2",
"imagesize",
"kurbo 0.13.1",
"lopdf",
"miniz_oxide 0.9.1",
"photocraft-affinity",
@@ -5766,7 +5767,7 @@ dependencies = [
"photocraft-psd",
"photocraft-raster",
"rayon",
"skrifa 0.44.0",
"skrifa 0.47.0",
]
[[package]]
@@ -9472,7 +9473,7 @@ dependencies = [
[[package]]
name = "winprint"
version = "0.2.1"
source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49"
source = "git+https://github.com/storytold/winprint.rs?rev=51934db382f225454cf152a8657eb03789be63c4#51934db382f225454cf152a8657eb03789be63c4"
dependencies = [
"flate2",
"fmt-derive",
@@ -10005,7 +10006,6 @@ dependencies = [
"nix",
"typed-path",
"windows-sys 0.61.2",
"zopfli",
]
[[package]]
@@ -10020,18 +10020,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zune-core"
version = "0.4.12"
+10 -10
View File
@@ -10,7 +10,7 @@ license = "MIT OR Apache-2.0"
rust-version = "1.95"
[workspace.dependencies]
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] }
# internal
photocraft-geom = { path = "crates/geom" }
photocraft-color = { path = "crates/color" }
@@ -39,13 +39,13 @@ photocraft-tablet = { path = "crates/tablet" }
photocraft-ipp = { path = "crates/ipp" }
# external
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["raster"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["raster"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
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"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = "1"
@@ -205,7 +205,7 @@ egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README).
hayro = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
+1 -1
View File
@@ -33,7 +33,7 @@ required-features = ["gpu"]
photocraft-automation = { path = "../../crates/automation" }
photocraft-doc = { workspace = true }
photocraft-engine = { workspace = true }
photocraft-io = { workspace = true }
photocraft-io = { workspace = true, features = ["pdf-editable"] }
photocraft-raster = { workspace = true }
photocraft-format = { path = "../../crates/format" }
photocraft-codecs = { workspace = true }
+4
View File
@@ -125,6 +125,10 @@ pub(crate) struct ConvertArgs {
/// PDF pages to import, 1-based: "3" or "2-7" (default all)
#[arg(long)]
pub(crate) pdf_pages: Option<String>,
/// Import PDF paths and embedded-font text as editable layers (experimental; unsupported
/// pages fall back to raster, and embedded fonts may change when edited or reopened)
#[arg(long)]
pub(crate) pdf_editable: bool,
#[command(flatten)]
pub(crate) gpu: GpuArgs,
#[command(flatten)]
+1
View File
@@ -46,6 +46,7 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write
psd_high_memory_approved: a.approve_high_memory,
pdf_dpi: a.pdf_dpi.unwrap_or(300.0),
pdf_pages: a.pdf_pages.as_deref().map(parse_pdf_pages).transpose()?,
pdf_editable: a.pdf_editable,
..Default::default()
};
let mut o = files::open_with_options(input, &import_opts)?;
+1 -1
View File
@@ -254,7 +254,7 @@ impl Backend for MacMenu {
pub fn install(ctx: &egui::Context, app: &photocraft_ui_egui::PhotocraftApp) -> Option<native_menu::NativeMenu> {
let language = &app.session.prefs().interface.language;
let lang = photocraft_ui_egui::i18n::Lang::from_pref(language);
let bar = native_menu::photocraft_layout(&photocraft_ui_egui::menus::menu_items(app), lang, language).bar;
let bar = native_menu::app_layout(app, &photocraft_ui_egui::menus::menu_items(app), lang, language).bar;
// Never crash for a menu: if AppKit refuses, keep the in-window menus.
let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let mut menu = MacMenu::new(ctx);
+2 -1
View File
@@ -68,7 +68,7 @@ const OPEN_FILTERS: &[(&str, &[&str])] = &[
("DPX and Cineon", &["dpx", "cin"]),
("Amiga IFF", &["iff", "lbm", "ilbm"]),
("DICOM", &["dcm", "dicom", "dc3"]),
("Camera Raw", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]),
("RAW images", &["dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf"]),
("Brushes", &["abr"]),
("Gradients", &["grd"]),
("Styles", &["asl"]),
@@ -763,6 +763,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
open_url: Some(Box::new(|url: &str| open::that(url).map_err(|e| e.to_string()))),
beep: Some(platform_beep),
check_updates: Some(crate::updates::service()),
last_update: Some(crate::updates::last_update),
clipboard_set_image: Some({
let clip = clip.clone();
guarded_clipboard_set(move |w: u32, h: u32, px: &[u8]| {
+3 -1
View File
@@ -218,7 +218,9 @@ fn open_filters_keep_literal_extensions_on_windows_and_macos() {
#[test]
fn native_services_provide_update_transport() {
assert!(native(None).check_updates.is_some());
let services = native(None);
assert!(services.check_updates.is_some());
assert!(services.last_update.is_some());
}
#[test]
+13
View File
@@ -20,6 +20,19 @@ pub fn service() -> CheckFn {
})
}
/// What the last self-update came to, once: `craft-update` removes its records as it reads them.
pub fn last_update() -> Option<Result<String, String>> {
use craft_update::self_update::{Outcome, current_version, take_outcome};
let app = &photocraft_ui_egui::UPDATE_APP;
let paths = craft_update::Paths::for_app(app).ok()?;
let version = photocraft_engine::build_info::VERSION;
let running = current_version(app, version).map_or_else(|| version.to_string(), |v| v.to_string());
match take_outcome(&paths, &running)? {
Outcome::Installed(installed) => Some(Ok(installed.to_string())),
Outcome::Failed(reason) => Some(Err(reason)),
}
}
fn check() -> CheckResult {
let http = craft_update::Http::new("PhotoCraft/Update")?;
let found = craft_update::check_for_update(&photocraft_ui_egui::UPDATE_APP, &http, photocraft_engine::build_info::VERSION)?;
+14
View File
@@ -0,0 +1,14 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="18" height="18" x="3" y="3" rx="2" />
<path d="M9 3v18" />
</svg>

After

Width:  |  Height:  |  Size: 284 B

+17
View File
@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Type options-bar glyph for vertical text (not from an icon set). -->
<path d="M3 20h18" />
<path d="M17 4v12" />
<path d="M12 10v6" />
<path d="M7 7v9" />
</svg>

After

Width:  |  Height:  |  Size: 395 B

+17
View File
@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Type options-bar glyph for vertical text (not from an icon set). -->
<path d="M3 12h18" />
<path d="M17 6v12" />
<path d="M12 9v6" />
<path d="M7 7v10" />
</svg>

After

Width:  |  Height:  |  Size: 395 B

+17
View File
@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<!-- PhotoCraft's own Type options-bar glyph for vertical text (not from an icon set). -->
<path d="M3 4h18" />
<path d="M17 8v12" />
<path d="M12 8v6" />
<path d="M7 8v9" />
</svg>

After

Width:  |  Height:  |  Size: 393 B

+7
View File
@@ -315,3 +315,10 @@ sync_github_name = false
[people.davidvhk]
real_name = "David Vanhoucke"
sync_github_name = true
[people.Kaedo17]
sync_github_name = true
[people.rmsff]
real_name = "Serikov Roman"
sync_github_name = false
+135
View File
@@ -0,0 +1,135 @@
//! Average changes colour, never coverage. Keep the existing RGB conversion and selection
//! weighting; Photoshop RGB8 observations are documented in docs/average-filter.md.
use photocraft_color::{PixelFormat, SampleType};
use photocraft_geom::Rect;
use photocraft_raster::{Interrupt, Surface, from_rgba_into, to_rgba};
use crate::{Ctx, Image};
#[derive(Default)]
struct Mean {
sum: [f64; 3],
weight: f64,
}
impl Mean {
fn add(&mut self, fmt: &PixelFormat, px: &[f32], coverage: f32) {
let rgba = to_rgba(fmt, px);
let w = f64::from(coverage);
for (sum, value) in self.sum.iter_mut().zip(rgba) {
*sum += f64::from(value) * w;
}
self.weight += w;
}
fn colour(&self) -> Option<[f32; 3]> {
(self.weight > 0.0).then(|| self.sum.map(|s| (s / self.weight) as f32))
}
}
fn mix(fmt: &PixelFormat, px: &mut [f32], colour: [f32; 3], coverage: f32) {
if coverage <= 0.0 {
return;
}
let mut rgba = to_rgba(fmt, px);
for (value, mean) in rgba.iter_mut().zip(colour) {
*value += (mean - *value) * coverage;
}
from_rgba_into(fmt, rgba, px);
}
// Rect's public coordinates can span more than i32::MAX. Reject these before raster helpers
// do their signed coordinate arithmetic, and cap a single operation's sample count.
fn valid_area(area: Rect, channels: usize) -> bool {
area.width() <= i32::MAX as u32
&& area.height() <= i32::MAX as u32
&& u64::from(area.width()).saturating_mul(u64::from(area.height())).saturating_mul(channels as u64) <= 512 * 1024 * 1024
}
pub(crate) fn apply(surface: &Surface, area: Rect, selection: Option<&Surface>, ctl: &Interrupt<'_>) -> Option<Surface> {
let fmt = surface.format();
let n = fmt.channels();
if !valid_area(area, n) || ctl.cancelled() {
return None;
}
if area.is_empty() {
return Some(surface.clone());
}
let mut raw = surface.try_read_region(area).ok()?;
let width = area.width() as usize;
let coverage = |i: usize| selection.map_or(1.0, |s| s.sample_channel(area.x0 + (i % width) as i32, area.y0 + (i / width) as i32, 0));
let mut mean = Mean::default();
for (i, px) in raw.chunks_exact(n).enumerate() {
if i % width == 0 && ctl.cancelled() {
return None;
}
mean.add(&fmt, px, coverage(i));
}
let Some(colour) = mean.colour() else { return Some(surface.clone()) };
for (i, px) in raw.chunks_exact_mut(n).enumerate() {
if i % width == 0 && ctl.cancelled() {
return None;
}
mix(&fmt, px, colour, coverage(i));
}
let mut out = surface.clone();
if ctl.cancelled() {
return None;
}
out.try_write_region(area, &raw).ok()?;
out.prune();
ctl.progress(1.0);
Some(out)
}
// The direct kernel API has no selection. Its mean is over the reference bounds, even when
// the requested output is only a tile; the surface dispatcher above also handles selections.
pub(crate) fn kernel(src: &Image, out: Rect, ctx: &Ctx) -> Vec<f32> {
let fmt = PixelFormat::new(ctx.mode, SampleType::F32, ctx.alpha);
let n = fmt.channels();
if src.ch != n || !valid_area(src.rect, n) || !valid_area(out, n) {
return Vec::new();
}
let read = |x: i32, y: i32| -> Option<&[f32]> {
if !src.rect.contains(x, y) {
return None;
}
let i = (i64::from(y) - i64::from(src.rect.y0)) as usize;
let j = (i64::from(x) - i64::from(src.rect.x0)) as usize;
let start = i.checked_mul(src.rect.width() as usize)?.checked_add(j)?.checked_mul(n)?;
src.data.get(start..start.checked_add(n)?)
};
let bounds = ctx.bounds.intersect(&src.rect);
let mut mean = Mean::default();
for y in bounds.y0..bounds.y1 {
for x in bounds.x0..bounds.x1 {
if let Some(px) = read(x, y) {
mean.add(&fmt, px, 1.0);
}
}
}
let len = (out.width() as usize).checked_mul(out.height() as usize).and_then(|s| s.checked_mul(n));
let Some(len) = len else { return Vec::new() };
let mut result = Vec::new();
if result.try_reserve_exact(len).is_err() {
return result;
}
let colour = mean.colour();
for y in out.y0..out.y1 {
for x in out.x0..out.x1 {
let mut px = [0.0; 5];
let Some(pixel) = px.get_mut(..n) else { return Vec::new() };
if let Some(source) = read(x, y) {
pixel.copy_from_slice(source);
}
if let Some(colour) = colour {
mix(&fmt, pixel, colour, 1.0);
}
result.extend_from_slice(pixel);
}
}
result
}
#[cfg(test)]
mod tests;
+59
View File
@@ -0,0 +1,59 @@
use super::*;
use photocraft_color::ColorMode;
#[test]
fn preserves_alpha_and_averages_hidden_rgb_at_each_depth() {
let bounds = Rect::new(0, 0, 2, 1);
for sample in SampleType::ALL {
let fmt = PixelFormat::new(ColorMode::Rgb, sample, true);
let mut surface = Surface::new(fmt);
surface.write_region(bounds, &[1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0]);
let out = apply(&surface, bounds, None, &Interrupt::NONE).unwrap();
for (i, p) in out.read_region(bounds).as_chunks::<4>().0.iter().enumerate() {
assert!((p[0] - 0.5).abs() <= 1.0 / 255.0);
assert_eq!(p[1], 0.0);
assert!((p[2] - 0.5).abs() <= 1.0 / 255.0);
assert_eq!(p[3], if i == 0 { 1.0 } else { 0.0 });
}
}
}
#[test]
fn direct_kernel_uses_reference_bounds_for_each_output_tile() {
let bounds = Rect::new(-1, 0, 1, 1);
let src = Image { rect: bounds, ch: 4, data: vec![1.0, 0.0, 0.0, 0.25, 0.0, 0.0, 1.0, 0.75] };
let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha: true };
assert_eq!(kernel(&src, Rect::new(-1, 0, 0, 1), &ctx), vec![0.5, 0.0, 0.5, 0.25]);
assert_eq!(kernel(&src, Rect::new(0, 0, 1, 1), &ctx), vec![0.5, 0.0, 0.5, 0.75]);
}
#[test]
fn rejects_extreme_geometry_and_honours_pre_cancel() {
let surface = Surface::new(PixelFormat::RGBA8);
let huge = Rect::new(i32::MIN, 0, i32::MAX, 1);
assert!(apply(&surface, huge, None, &Interrupt::NONE).is_none());
assert!(apply(&surface, Rect::new(0, 0, 5, 5), None, &Interrupt::cancel_only(&|| true)).is_none());
assert_eq!(surface.tile_count(), 0);
}
#[test]
fn soft_selection_weights_the_mean_and_output_mix() {
let bounds = Rect::new(0, 0, 2, 1);
for sample in SampleType::ALL {
let mut surface = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
surface.write_region(bounds, &[1.0, 0.0, 0.0, 0.25, 0.0, 0.0, 1.0, 0.75]);
let before = surface.read_region(bounds);
let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
selection.write_region(bounds, &[0.25, 1.0]);
let out = apply(&surface, bounds, Some(&selection), &Interrupt::NONE).unwrap();
// Unequal coverage makes the mean [0.2, 0, 0.8]. Each pixel then mixes
// toward it using its own coverage, independently of its original alpha.
for (i, expected) in [[0.8, 0.0, 0.2], [0.2, 0.0, 0.8]].iter().enumerate() {
let pixel = out.pixel(i as i32, 0);
for (actual, expected) in pixel.iter().zip(expected) {
assert!((actual - expected).abs() <= 1.0 / 255.0, "{sample:?}: {pixel:?}");
}
assert_eq!(pixel[3], before[i * 4 + 3]);
}
}
}
+13 -3
View File
@@ -21,6 +21,7 @@
pub mod art_history;
mod artistic;
mod artistic_fx;
mod average;
mod blur;
mod blur2;
pub mod camera_raw;
@@ -208,6 +209,8 @@ pub enum PolarMode {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "filter", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum FilterParams {
/// Mean colour over the selected area, retaining each pixel's alpha.
Average,
/// Radius = Gaussian standard deviation in pixels (0.1–1000).
GaussianBlur {
radius: f32,
@@ -592,7 +595,8 @@ impl FilterParams {
FilterParams::Emboss { height, .. } => Halo::Radius(height.abs().ceil() as i32 + 2),
FilterParams::FindEdges => Halo::Radius(1),
FilterParams::AddNoise { .. } | FilterParams::Solarize | FilterParams::Invert | FilterParams::Desaturate => Halo::Radius(0),
FilterParams::RadialBlur { .. }
FilterParams::Average
| FilterParams::RadialBlur { .. }
| FilterParams::Offset { .. }
| FilterParams::Twirl { .. }
| FilterParams::Pinch { .. }
@@ -634,14 +638,16 @@ impl FilterParams {
}
/// Whether the filter places and sizes its pattern by the canvas even with a selection
/// (Clouds, Fibers): its bounds are then the canvas, and the selection only masks the result.
/// (Clouds, Fibers), or limits its working area to the canvas (Average). The output
/// area is still clipped to the selection; Average also weights its mean by that coverage.
pub fn sizes_by_canvas(&self) -> bool {
matches!(self, FilterParams::Clouds { .. } | FilterParams::Fibers { .. })
matches!(self, FilterParams::Average | FilterParams::Clouds { .. } | FilterParams::Fibers { .. })
}
/// Human-readable name.
pub fn label(&self) -> &'static str {
match self {
FilterParams::Average => "Average",
FilterParams::GaussianBlur { .. } => "Gaussian Blur",
FilterParams::BoxBlur { .. } => "Box Blur",
FilterParams::MotionBlur { .. } => "Motion Blur",
@@ -766,6 +772,7 @@ pub struct Ctx {
/// the halo, or the bounds for global filters). Returns interleaved samples.
pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec<f32> {
match params {
FilterParams::Average => average::kernel(src, out, ctx),
FilterParams::GaussianBlur { radius } => blur::gaussian(src, out, ctx, *radius),
FilterParams::BoxBlur { radius } => blur::boxed(src, out, ctx, *radius),
FilterParams::MotionBlur { angle, distance } => blur::motion(src, out, ctx, *angle, *distance),
@@ -1141,6 +1148,9 @@ fn apply_tiled_with_impl(
if area.is_empty() {
return Some(out);
}
if matches!(params, FilterParams::Average) {
return average::apply(surface, extent.map_or(area, |e| area.intersect(&e)), selection, ctl);
}
#[cfg(not(target_arch = "wasm32"))]
if prepare_fast_paths && let Some(result) = sharpen::fft::apply(surface, params, area, selection, extent, ctl) {
return result;
+182 -19
View File
@@ -112,7 +112,15 @@ fn d_rate() -> f64 {
}
/// One brush stroke: the tool, its brush options and the points it passed through
/// (`[x, y]` or `[x, y, pressure 0..1]`, document pixels).
/// (`[x, y]`, `[x, y, pressure 0..1]` or `[x, y, pressure 0..1, ms]`, document pixels).
///
/// A fourth number makes the point *live*: the milliseconds since the previous point, as the
/// interactive dialog records them. A segment ending on a live point follows the pointer exactly
/// (Forward Warp and Push Left also show the motion since their last dab, as a provisional dab
/// taken back before the next point, instead of waiting for the next dab spacing) and the
/// stationary tools work by elapsed time as well as distance, so the brush keeps working at the
/// same speed when it moves slowly or the frame rate changes. Points without it (older strokes,
/// scripts) replay exactly as they always have.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LiquifyStroke {
@@ -144,20 +152,28 @@ impl LiquifyStroke {
LiquifyStroke { tool, size, density: d_density(), pressure: d_pressure(), rate: d_rate(), points: Vec::new(), amount: None }
}
/// Validates the stroke (finite numbers, 2 or 3 per point).
/// Validates the stroke (finite numbers, 2 to 4 per point).
pub fn validate(&self) -> Result<(), String> {
if !(self.size.is_finite() && self.size >= 1.0 && self.size <= 15000.0) {
return Err(format!("brush size {} out of range 1..15000", self.size));
}
for p in &self.points {
if !(2..=3).contains(&p.len()) || p.iter().any(|v| !v.is_finite()) {
return Err("stroke points are [x, y] or [x, y, pressure]".into());
if !(2..=4).contains(&p.len()) || p.iter().any(|v| !v.is_finite()) {
return Err("stroke points are [x, y], [x, y, pressure] or [x, y, pressure, ms]".into());
}
}
Ok(())
}
}
/// Milliseconds of holding a stationary tool still that one full-strength dab stands for (the
/// 30 dabs a second the dialog has always used).
const HELD_DAB_MS: f64 = 1000.0 / 30.0;
/// Most elapsed time one live point counts for: after a stall (a slow frame, the app in the
/// background) the brush catches up by this much at most instead of lurching.
pub const MAX_LIVE_MS: f64 = 250.0;
/// The displacement field plus the freeze mask, over `bounds` (document pixels).
#[derive(Clone, Debug)]
pub struct LiquifyField {
@@ -172,6 +188,21 @@ pub struct LiquifyField {
pub freeze: Vec<f32>,
/// Where the brush stroke in progress stands, so dab spacing runs on across its segments.
cursor: Option<StrokeCursor>,
/// The provisional dab a live Forward Warp / Push Left segment ended with, to take back
/// before the stroke goes on (see [`Self::stroke_segment_live`]).
tail: Option<LiveTail>,
}
/// What a live segment's closing dab overwrote: the displacements `saved` of the nodes in columns
/// `i0..=i1`, one row after another from row `j0`, as they were, and the document rectangle the
/// dab touched.
#[derive(Clone, Debug)]
struct LiveTail {
i0: usize,
j0: usize,
i1: usize,
saved: Vec<[f32; 2]>,
dirty: Rect,
}
/// Two fields are equal when their displacement and freeze mask are: the stroke cursor is
@@ -230,7 +261,7 @@ impl LiquifyField {
cell *= 2.0;
(w, h) = nodes(cell);
}
LiquifyField { bounds, cell, w, h, d: vec![[0.0; 2]; w * h], freeze: vec![0.0; w * h], cursor: None }
LiquifyField { bounds, cell, w, h, d: vec![[0.0; 2]; w * h], freeze: vec![0.0; w * h], cursor: None, tail: None }
}
/// Document position of node (i, j) (node 0 sits on the first pixel centre).
@@ -245,6 +276,27 @@ impl LiquifyField {
((x - f64::from(self.bounds.x0) - 0.5) / self.cell, (y - f64::from(self.bounds.y0) - 0.5) / self.cell)
}
/// The field nodes a dab of radius `r` at `c` can touch, as `(i0, j0, i1, j1)` inclusive;
/// `None` when it touches none (off the grid, or a NaN centre).
fn node_span(&self, c: [f64; 2], r: f64) -> Option<(usize, usize, usize, usize)> {
let (gx0, gy0) = self.to_grid(c[0] - r, c[1] - r);
let (gx1, gy1) = self.to_grid(c[0] + r, c[1] + r);
// Decide the overlap in f64, before any conversion to an index: a far-off centre saturated
// `as usize` to `usize::MAX`, which read back as `-1` passed the overlap check. Written so
// that NaN, which fails every comparison, touches nothing (`max`/`min` would hide it).
let (wmax, hmax) = (self.w as f64 - 1.0, self.h as f64 - 1.0);
if !(gx1.ceil() >= 0.0 && gy1.ceil() >= 0.0 && gx0.floor() <= wmax && gy0.floor() <= hmax) {
return None;
}
let (x0, y0) = (gx0.floor().max(0.0), gy0.floor().max(0.0));
let (x1, y1) = (gx1.ceil().min(wmax), gy1.ceil().min(hmax));
if !(x0 <= x1 && y0 <= y1) {
return None;
}
// Now 0 <= x0 <= x1 <= w - 1 (and likewise in y): whole numbers that convert exactly.
Some((x0 as usize, y0 as usize, x1 as usize, y1 as usize))
}
pub fn is_identity(&self) -> bool {
self.d.iter().all(|v| v[0] == 0.0 && v[1] == 0.0)
}
@@ -274,6 +326,7 @@ impl LiquifyField {
/// Applies one stroke. Returns the document rectangle whose output changed.
pub fn apply_stroke(&mut self, s: &LiquifyStroke) -> Rect {
self.cursor = None;
self.tail = None;
match s.tool {
LiquifyTool::LassoMask => return self.apply_lasso(s),
LiquifyTool::ReconstructAll => {
@@ -293,11 +346,18 @@ impl LiquifyField {
if s.tool.is_global() {
return self.bounds;
}
let pts: Vec<[f64; 3]> = s.points.iter().filter(|p| p.len() >= 2).map(|p| [p[0], p[1], p.get(2).copied().unwrap_or(1.0)]).collect();
let Some(&first) = pts.first() else { return Rect::EMPTY };
// Each point with its live time (the fourth number), if it has one.
let pts: Vec<([f64; 3], Option<f64>)> =
s.points.iter().filter(|p| p.len() >= 2).map(|p| ([p[0], p[1], p.get(2).copied().unwrap_or(1.0)], p.get(3).copied())).collect();
let Some(&(first, _)) = pts.first() else { return Rect::EMPTY };
let mut dirty = self.stroke_begin(s, first);
for w in pts.windows(2) {
dirty = dirty.union(&self.stroke_segment(s, w[0], w[1]));
let ((a, _), (b, ms)) = (w[0], w[1]);
let d = match ms {
Some(ms) => self.stroke_segment_live(s, a, b, ms),
None => self.stroke_segment(s, a, b),
};
dirty = dirty.union(&d);
}
dirty
}
@@ -360,6 +420,7 @@ impl LiquifyField {
/// callers use this plus [`Self::stroke_segment`] per new point, which is exactly what
/// [`Self::apply_stroke`] does with the whole point list.
pub fn stroke_begin(&mut self, s: &LiquifyStroke, p: [f64; 3]) -> Rect {
self.tail = None;
self.cursor = Some(StrokeCursor { end: [p[0], p[1]], last_dab: [p[0], p[1]], carry: 0.0 });
if s.tool.is_stationary() && !s.tool.is_global() { self.dab(s, [p[0], p[1]], [0.0, 0.0], p[2].clamp(0.0, 1.0), 1.0) } else { Rect::EMPTY }
}
@@ -370,7 +431,118 @@ impl LiquifyField {
/// stationary tool held still dabs once at `b`. When `a` is not where the previous segment
/// ended, the stroke starts afresh at `a`.
pub fn stroke_segment(&mut self, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3]) -> Rect {
self.walk_segment(s, a, b, true)
let undone = self.undo_tail();
undone.union(&self.walk_segment(s, a, b, true))
}
/// Continues a stroke from `a` to a live point `b` reached `ms` milliseconds after `a` (see
/// [`LiquifyStroke`]), which is what the interactive dialog records for every pointer event.
///
/// Forward Warp and Push Left walk the segment as [`Self::stroke_segment`] does, so the dabs
/// fall every dab spacing of distance travelled however finely the pointer was sampled. Then
/// what is left of the motion since the last dab is applied as one shorter, *provisional* dab,
/// so the image follows the pointer on every event. That dab is taken back (see
/// [`Self::undo_tail`]) before the next segment, so only the regular dabs stay and a slow and
/// a fast pointer give the same warp, apart from the final partial dab.
///
/// The stationary tools (Twirl, Pucker, Bloat, Reconstruct, Smooth, Freeze, Thaw) apply the
/// larger of what the elapsed time is worth ([`HELD_DAB_MS`] per full dab, at most
/// [`MAX_LIVE_MS`] per point) and what the distance travelled is worth (as a moving stroke
/// always has), spread evenly along the segment in dabs of at most full strength. Held still,
/// slow or fast, at any frame rate, the brush works continuously at one speed.
pub fn stroke_segment_live(&mut self, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3], ms: f64) -> Rect {
self.walk_segment_live(s, a, b, ms, true)
}
/// Takes back the provisional closing dab of the last live segment, if any. Returns the
/// document rectangle that changed.
fn undo_tail(&mut self) -> Rect {
let Some(t) = self.tail.take() else { return Rect::EMPTY };
let n = t.i1 - t.i0 + 1;
for (row, saved) in t.saved.chunks_exact(n).enumerate() {
let at = (t.j0 + row) * self.w + t.i0;
self.d[at..at + n].copy_from_slice(saved);
}
t.dirty
}
/// [`Self::stroke_segment_live`]; `skip` as in [`Self::walk_segment`].
fn walk_segment_live(&mut self, s: &LiquifyStroke, a: [f64; 3], b: [f64; 3], ms: f64, skip: bool) -> Rect {
let mut dirty = self.undo_tail();
if !s.tool.is_stationary() {
dirty = dirty.union(&self.walk_segment(s, a, b, skip));
// What the dab spacing left over: show it now, and take it back on the next event.
if let Some(cur) = self.cursor
&& cur.end == [b[0], b[1]]
{
let delta = [b[0] - cur.last_dab[0], b[1] - cur.last_dab[1]];
let pressure = b[2].clamp(0.0, 1.0);
// A dab with no strength changes nothing, so there is nothing to take back.
if (delta[0] != 0.0 || delta[1] != 0.0) && pressure > 0.0 && s.pressure > 0.0 {
let r = (s.size / 2.0).max(0.5);
let span = self.node_span(cur.last_dab, r);
let saved = span.map(|(i0, j0, i1, j1)| {
let mut v = Vec::with_capacity((i1 - i0 + 1) * (j1 - j0 + 1));
for j in j0..=j1 {
v.extend_from_slice(&self.d[j * self.w + i0..=j * self.w + i1]);
}
v
});
let tail = self.dab(s, cur.last_dab, delta, pressure, 1.0);
if let (Some((i0, j0, i1, _)), Some(saved)) = (span, saved) {
self.tail = Some(LiveTail { i0, j0, i1, saved, dirty: tail });
}
dirty = dirty.union(&tail);
}
}
return dirty;
}
// A live stroke keeps no spacing state for these tools; the cursor only marks continuity.
self.cursor = Some(StrokeCursor { end: [b[0], b[1]], last_dab: [b[0], b[1]], carry: 0.0 });
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let len = dx.hypot(dy);
if !len.is_finite() || !b[0].is_finite() || !b[1].is_finite() {
self.cursor = None;
return dirty;
}
let (pa, pb) = (a[2].clamp(0.0, 1.0), b[2].clamp(0.0, 1.0));
let r = (s.size / 2.0).max(0.5);
let spacing = dab_spacing(r);
let ms = if ms.is_finite() { ms.clamp(0.0, MAX_LIVE_MS) } else { 0.0 };
// The same strength per distance a moving stationary tool has always had: `moving_weight`
// per dab spacing.
let by_time = ms / HELD_DAB_MS;
let by_distance = len / spacing * moving_weight(r);
let total = by_time.max(by_distance);
if total <= 0.0 {
return dirty;
}
// Enough dabs that none is stronger than a full one or further apart than the spacing.
let n = total.ceil().max((len / spacing).ceil()).max(1.0);
let weight = total / n;
let at = |k: f64| {
let t = (k + 1.0) / n;
([a[0] + dx * t, a[1] + dy * t], pa + (pb - pa) * t)
};
let (mut k0, mut k1) = (0.0f64, n - 1.0);
if skip && len > 0.0 {
// Only dabs near the part of the segment that can reach a node (#937).
match self.reachable_span(a, [dx, dy], len, r) {
Some((d0, d1)) => {
k0 = k0.max((d0 / len * n).floor() - 2.0);
k1 = k1.min((d1 / len * n).ceil() + 1.0);
}
None => return dirty,
}
}
if k0 > k1 {
return dirty;
}
for k in (k0 as u64)..=(k1 as u64) {
let (c, p) = at(k as f64);
dirty = dirty.union(&self.dab(s, c, [0.0, 0.0], p, weight));
}
dirty
}
/// [`Self::stroke_segment`]; `skip` leaves out the dabs that cannot reach a field node (they
@@ -479,16 +651,7 @@ impl LiquifyField {
if strength <= 0.0 {
return Rect::EMPTY;
}
let (gx0, gy0) = self.to_grid(c[0] - r, c[1] - r);
let (gx1, gy1) = self.to_grid(c[0] + r, c[1] + r);
let i0 = gx0.floor().max(0.0) as usize;
let j0 = gy0.floor().max(0.0) as usize;
let i1 = (gx1.ceil().max(-1.0) as isize).min(self.w as isize - 1);
let j1 = (gy1.ceil().max(-1.0) as isize).min(self.h as isize - 1);
if i1 < i0 as isize || j1 < j0 as isize {
return Rect::EMPTY;
}
let (i1, j1) = (i1 as usize, j1 as usize);
let Some((i0, j0, i1, j1)) = self.node_span(c, r) else { return Rect::EMPTY };
// Snapshot of the affected nodes plus a margin (sampling reads around them).
let m = ((delta[0].abs().max(delta[1].abs()) + r * 0.2) / self.cell).ceil() as usize + 2;
let (si0, sj0) = (i0.saturating_sub(m), j0.saturating_sub(m));
+260
View File
@@ -138,6 +138,52 @@ fn a_segment_to_a_far_off_point_returns() {
f.stroke_segment(&LiquifyStroke::new(LiquifyTool::Bloat, 30.0), [5.0, -1e15, 1.0], [5.0, 1e15, 1.0]);
}
/// A timed (live) stroke far off the field leaves it unchanged instead of panicking. The
/// provisional closing dab used to take its node span from a far-off centre: the lower index
/// saturated to `usize::MAX`, read as `-1` it passed the overlap check, and the snapshot then
/// subtracted past zero (debug) or sliced out of range (release).
#[test]
fn a_timed_stroke_far_off_the_field_leaves_it_unchanged() {
let far = [
// The review's case: valid points, both far off on the right.
vec![vec![1e30, 3.0, 1.0], vec![1e30, 3.25, 1.0, 16.0]],
vec![vec![3.0, 1e30, 1.0], vec![3.25, 1e30, 1.0, 16.0]],
vec![vec![1e30, 1e30, 1.0], vec![1e30, 1e30 + 1e15, 1.0, 16.0]],
vec![vec![-1e30, 3.0, 1.0], vec![-1e30, 3.25, 1.0, 16.0]],
vec![vec![3.0, -1e30, 1.0], vec![3.25, -1e30, 1.0, 16.0]],
vec![vec![f64::MAX, 3.0, 1.0], vec![f64::MAX, 3.25, 1.0, 16.0]],
];
use LiquifyTool::*;
for tool in [ForwardWarp, Reconstruct, Smooth, TwirlCw, TwirlCcw, Pucker, Bloat, PushLeft, Freeze, Thaw] {
for points in &far {
let mut s = LiquifyStroke::new(tool, 30.0);
s.points = points.clone();
s.validate().unwrap();
let mut f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0);
f.apply_stroke(&s);
let fresh = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0);
assert!(f.d == fresh.d && f.freeze == fresh.freeze, "{tool:?} {points:?} changed the field");
}
}
}
/// `node_span` decides off the grid before converting to indices, on every side.
#[test]
fn node_span_rejects_spans_off_the_grid() {
let f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0);
for c in [[1e30, 3.0], [3.0, 1e30], [-1e30, 3.0], [3.0, -1e30], [f64::MAX, f64::MAX], [-f64::MAX, 3.0], [f64::NAN, 3.0], [3.0, f64::INFINITY]] {
assert_eq!(f.node_span(c, 15.0), None, "{c:?}");
}
// On the grid, and partly off it, the span is the nodes inside it.
let (w, h) = (f.w - 1, f.h - 1);
assert_eq!(f.node_span([12.0, 8.0], 1e6), Some((0, 0, w, h)));
let Some((i0, j0, i1, j1)) = f.node_span([12.0, 8.0], 3.0) else { panic!("a dab on the field touches it") };
assert!(i0 <= i1 && i1 <= w && j0 <= j1 && j1 <= h, "{:?}", (i0, j0, i1, j1));
let Some((i0, _, i1, _)) = f.node_span([-10.0, 8.0], 12.0) else { panic!("a dab reaching the left edge touches it") };
assert_eq!(i0, 0);
assert!(i1 <= w);
}
fn sample(st: SampleType) -> Surface {
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, st, true));
for y in 0..64 {
@@ -530,3 +576,217 @@ fn proxy_matches_the_full_render_roughly() {
}
assert!(bad < 96 * 64 / 50, "{bad}");
}
// ---- Live strokes: the brush follows the pointer in real time ----
/// `path` as live points, one event per `step` px along each leg, `ms` apart.
fn live(path: &[[f64; 2]], step: f64, ms: f64) -> Vec<Vec<f64>> {
let mut out = vec![vec![path[0][0], path[0][1], 1.0, 0.0]];
for w in path.windows(2) {
let (a, b) = (w[0], w[1]);
let n = ((b[0] - a[0]).hypot(b[1] - a[1]) / step).ceil().max(1.0) as usize;
for k in 1..=n {
let t = k as f64 / n as f64;
out.push(vec![a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, 1.0, ms]);
}
}
out
}
fn max_diff(a: &LiquifyField, b: &LiquifyField) -> f32 {
a.d.iter().zip(&b.d).map(|(p, q)| (p[0] - q[0]).abs().max((p[1] - q[1]).abs())).fold(0.0f32, f32::max)
}
/// The user's report: moving the mouse slowly, Liquify only changed the image once every dab
/// spacing (a twentieth of the brush radius, 10 px for a 400 px brush), not with every movement.
/// A live point now applies all the motion up to it, so every pointer event moves the image.
#[test]
fn a_slow_live_drag_moves_the_image_on_every_pointer_event() {
for tool in [LiquifyTool::ForwardWarp, LiquifyTool::PushLeft] {
let s = LiquifyStroke::new(tool, 200.0); // spacing 5 px
let mut f = LiquifyField::new(Rect::new(0, 0, 300, 200), 2.0);
let mut legacy = f.clone();
let start = [100.0, 100.0, 1.0];
f.stroke_begin(&s, start);
legacy.stroke_begin(&s, start);
let (mut prev, mut moves, mut legacy_moves) = (start, 0, 0);
// A crawl: half a pixel per event, 20 events (10 px, two spacings).
for k in 1..=20 {
let p = [100.0 + k as f64 * 0.5, 100.0, 1.0];
let (before, legacy_before) = (f.d.clone(), legacy.d.clone());
f.stroke_segment_live(&s, prev, p, 16.0);
legacy.stroke_segment(&s, prev, p);
moves += usize::from(f.d != before);
legacy_moves += usize::from(legacy.d != legacy_before);
prev = p;
}
assert_eq!(moves, 20, "{tool:?}: every event moves the image");
assert!(legacy_moves <= 3, "{tool:?}: the legacy walk only moved it once per spacing ({legacy_moves})");
// And all the motion is there: the centre has been pushed (almost) as far as the brush went.
let d = f.sample(105.0, 100.0);
let shift = if tool == LiquifyTool::ForwardWarp { -d[0] } else { d[1].abs() };
assert!(shift > 7.0, "{tool:?}: pushed {shift} px for a 10 px drag");
}
}
/// Following the pointer exactly must not bring back #2606's problem (a slow and a fast pointer
/// giving different warps): the two differ by a small fraction of the displacement.
#[test]
fn live_drags_sampled_finely_or_coarsely_agree_closely() {
let path = [[40.0, 40.0], [180.0, 60.0], [200.0, 150.0], [60.0, 160.0]];
for (tool, size) in [(LiquifyTool::ForwardWarp, 60.0), (LiquifyTool::ForwardWarp, 200.0), (LiquifyTool::PushLeft, 80.0)] {
let field = |step: f64| {
let mut s = LiquifyStroke::new(tool, size);
s.points = live(&path, step, 16.0);
LiquifyField::from_strokes(Rect::new(0, 0, 260, 220), 2.0, &[s])
};
let (slow, fast) = (field(0.7), field(25.0));
let deep = slow.max_displacement();
let dd = max_diff(&slow, &fast);
assert!(deep > 10.0 && dd < deep * 0.1, "{tool:?} {size}px: slow and fast differ by {dd} px of {deep}");
}
}
/// Holding a stationary tool still works by elapsed time, not by how often frames come: one
/// second at 30, 60 or 144 frames a second does the same.
#[test]
fn held_stationary_tools_work_at_the_same_speed_at_any_frame_rate() {
for tool in [LiquifyTool::TwirlCw, LiquifyTool::Bloat, LiquifyTool::Pucker] {
let field = |fps: f64| {
let mut s = LiquifyStroke::new(tool, 80.0);
let frames = fps as usize; // one second
s.points = std::iter::once(vec![100.0, 100.0, 1.0, 0.0]).chain((0..frames).map(|_| vec![100.0, 100.0, 1.0, 1000.0 / fps])).collect();
LiquifyField::from_strokes(Rect::new(0, 0, 200, 200), 2.0, &[s])
};
let (a, b, c) = (field(30.0), field(60.0), field(144.0));
let deep = a.max_displacement();
assert!(deep > 3.0, "{tool:?}: a second's hold does something ({deep} px)");
for (fps, f) in [(60, &b), (144, &c)] {
let dd = max_diff(&a, f);
assert!(dd < deep * 0.08, "{tool:?}: {fps} fps differs from 30 fps by {dd} px of {deep}");
}
}
}
/// The other half of the report: a stationary tool crept along slowly did nothing at all (the
/// still-brush timer kept resetting and the distance never reached a dab spacing). Live, it works
/// at least as fast as held still.
#[test]
fn a_creeping_stationary_tool_keeps_working() {
let s = LiquifyStroke::new(LiquifyTool::TwirlCw, 120.0); // spacing 3 px
let mut f = LiquifyField::new(Rect::new(0, 0, 240, 200), 2.0);
f.stroke_begin(&s, [100.0, 100.0, 1.0]);
let mut prev = [100.0, 100.0, 1.0];
let mut changed = 0;
for k in 1..=30 {
let p = [100.0 + k as f64 * 0.2, 100.0, 1.0];
let before = f.d.clone();
f.stroke_segment_live(&s, prev, p, 16.7);
changed += usize::from(f.d != before);
prev = p;
}
assert_eq!(changed, 30, "every frame twirls a little more");
assert!(f.max_displacement() > 3.0, "half a second of creeping twirls visibly ({})", f.max_displacement());
}
/// Live strokes replay to exactly the field the interactive calls built (what OK relies on), and
/// a stall is capped instead of lurching.
#[test]
fn live_strokes_replay_exactly_and_stalls_are_capped() {
for tool in [LiquifyTool::ForwardWarp, LiquifyTool::TwirlCcw, LiquifyTool::Smooth, LiquifyTool::Freeze, LiquifyTool::Reconstruct] {
let mut s = LiquifyStroke::new(tool, 50.0);
s.points = live(&[[30.0, 30.0], [90.0, 70.0], [40.0, 90.0]], 1.3, 9.0);
let mut warp = LiquifyStroke::new(LiquifyTool::ForwardWarp, 60.0);
warp.points = vec![vec![40.0, 40.0], vec![80.0, 70.0]];
let mut f = LiquifyField::from_strokes(bounds(), 2.0, std::slice::from_ref(&warp));
let pts: Vec<[f64; 3]> = s.points.iter().map(|p| [p[0], p[1], p[2]]).collect();
f.stroke_begin(&s, pts[0]);
for (k, w) in pts.windows(2).enumerate() {
f.stroke_segment_live(&s, w[0], w[1], s.points[k + 1][3]);
}
assert_eq!(f, LiquifyField::from_strokes(bounds(), 2.0, &[warp, s]), "{tool:?}");
}
let s = LiquifyStroke::new(LiquifyTool::Bloat, 60.0);
let (mut stall, mut capped) = (LiquifyField::new(bounds(), 2.0), LiquifyField::new(bounds(), 2.0));
stall.stroke_segment_live(&s, [50.0, 50.0, 1.0], [50.0, 50.0, 1.0], 60_000.0);
capped.stroke_segment_live(&s, [50.0, 50.0, 1.0], [50.0, 50.0, 1.0], MAX_LIVE_MS);
assert_eq!(stall, capped);
// Hostile values neither panic nor hang.
let mut f = LiquifyField::new(Rect::new(0, 0, 24, 16), 2.0);
for tool in [LiquifyTool::ForwardWarp, LiquifyTool::Bloat, LiquifyTool::Freeze] {
let s = LiquifyStroke::new(tool, 30.0);
f.stroke_segment_live(&s, [0.0, 0.0, 1.0], [1e15, 0.0, 1.0], 16.0);
f.stroke_segment_live(&s, [5.0, -1e15, 1.0], [5.0, 1e15, 1.0], f64::NAN);
f.stroke_segment_live(&s, [-1e308, 5.0, 1.0], [1e308, 5.0, 1.0], -5.0);
f.stroke_segment_live(&s, [f64::NAN, 3.0, 1.0], [4.0, f64::INFINITY, 1.0], f64::INFINITY);
}
let mut bad = LiquifyStroke::new(LiquifyTool::ForwardWarp, 30.0);
bad.points = vec![vec![1.0, 2.0, 1.0, 16.0, 9.0]];
assert!(bad.validate().is_err());
bad.points = vec![vec![1.0, 2.0, 1.0, 16.0]];
assert!(bad.validate().is_ok());
}
/// Old strokes (no times) replay bit for bit as before: the live path is opt-in per point.
#[test]
fn strokes_without_times_replay_as_before() {
let path = [[20.0, 20.0, 1.0], [62.0, 26.0, 0.6], [70.0, 50.0, 0.9]];
for tool in [LiquifyTool::ForwardWarp, LiquifyTool::TwirlCw, LiquifyTool::Freeze] {
let mut s = LiquifyStroke::new(tool, 30.0);
s.points = sampled(&path, 7);
let mut f = LiquifyField::new(bounds(), 2.0);
let pts: Vec<[f64; 3]> = s.points.iter().map(|p| [p[0], p[1], p[2]]).collect();
f.stroke_begin(&s, pts[0]);
for w in pts.windows(2) {
f.stroke_segment(&s, w[0], w[1]);
}
assert_eq!(f, LiquifyField::from_strokes(bounds(), 2.0, &[s]), "{tool:?}");
}
}
/// A live segment with no strength changes nothing, so it leaves no provisional dab to take back;
/// with strength it does. No strength is a zero pressure at the point or a zero stroke pressure.
#[test]
fn a_live_segment_without_strength_leaves_nothing_to_take_back() {
for (point_pressure, stroke_pressure, shown) in [(0.0, 100.0, false), (1.0, 0.0, false), (1.0, 100.0, true)] {
let mut s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 200.0);
s.pressure = stroke_pressure;
let mut f = LiquifyField::new(Rect::new(0, 0, 300, 200), 2.0);
f.stroke_begin(&s, [100.0, 100.0, point_pressure]);
f.stroke_segment_live(&s, [100.0, 100.0, point_pressure], [100.5, 100.0, point_pressure], 16.0);
let case = format!("point pressure {point_pressure}, stroke pressure {stroke_pressure}");
assert_eq!(f.tail.is_some(), shown, "{case}");
assert_eq!(f.is_identity(), !shown, "{case}");
}
}
/// The provisional dab of one live segment is taken back before the next: a field reused across two
/// segments has a tail after the first, and none after a second segment that has no strength, which
/// also reports the taken-back area as changed so the caller repaints it. A second segment with
/// strength takes it back too: the result is the same as one segment straight to the same point.
#[test]
fn the_next_live_segment_takes_back_the_provisional_dab() {
let s = LiquifyStroke::new(LiquifyTool::ForwardWarp, 200.0);
let field = || {
let mut f = LiquifyField::new(Rect::new(0, 0, 300, 200), 2.0);
f.stroke_begin(&s, [100.0, 100.0, 1.0]);
let first = f.stroke_segment_live(&s, [100.0, 100.0, 1.0], [100.5, 100.0, 1.0], 16.0);
(f, first)
};
let (mut f, first) = field();
assert!(f.tail.is_some(), "the first segment leaves a provisional dab");
assert!(!f.is_identity());
let undone = f.stroke_segment_live(&s, [100.5, 100.0, 1.0], [100.5, 100.0, 0.0], 16.0);
assert!(!undone.is_empty(), "the taken-back dab is reported as changed");
assert_eq!(undone.union(&first), undone, "and its area covers what the first segment repainted");
assert!(f.tail.is_none(), "the next segment took it back");
assert!(f.is_identity(), "and nothing of it is left in the field");
let (mut g, _) = field();
g.stroke_segment_live(&s, [100.5, 100.0, 1.0], [101.0, 100.0, 1.0], 16.0);
assert!(g.tail.is_some(), "the second segment leaves its own provisional dab");
let mut direct = LiquifyField::new(Rect::new(0, 0, 300, 200), 2.0);
direct.stroke_begin(&s, [100.0, 100.0, 1.0]);
direct.stroke_segment_live(&s, [100.0, 100.0, 1.0], [101.0, 100.0, 1.0], 16.0);
assert!(g == direct, "the first segment's dab was taken back before the second was applied");
}
+103 -50
View File
@@ -219,11 +219,44 @@ pub fn magic_wand(px: &[[f32; 4]], area: Rect, seed: (i32, i32), tolerance: f32,
}
}
if anti_alias {
antialias(&mut m, w, h);
let tol = (tolerance + 1e-3).floor().max(0.0);
let src = m.clone();
for (i, v) in m.iter_mut().enumerate() {
if src[i] == 0.0 && touches_region(i % w, i / w, w, h, |x, y| src[y * w + x] > 0.0) {
let p = px[i];
let over = (0..3).map(|c| (p[c] - target[c]).abs() * 255.0).fold(0.0f32, f32::max) - tol;
*v = f32::from(fringe_coverage(over, p[3].min(target[3]) * 255.0)) / 255.0;
}
}
}
m
}
/// How many levels past the tolerance the anti-aliased fringe fades over, from fully selected to
/// nothing. Measured in the reference application (#11776): 3 levels past gives 251, 5 gives
/// 249 and 123 gives 110; a straight fade to zero at 216 levels gives all three.
const FRINGE_LEVELS: f32 = 216.0;
/// Coverage (0–255) of an anti-aliased fringe pixel: a neighbour of the region whose most
/// different colour channel is `over` levels past the tolerance, and `alpha` (0–255) the lower
/// of its and the clicked pixel's opacity. Photoshop keeps the region itself fully selected and
/// softens only the pixels just outside it, fading with the distance past the tolerance; a
/// neighbour without colour (transparent, next to a shape on its own layer) gets none.
fn fringe_coverage(over: f32, alpha: f32) -> u8 {
let k = (1.0 - over.max(0.0) / FRINGE_LEVELS).clamp(0.0, 1.0) * (alpha / 255.0).clamp(0.0, 1.0);
(k * 255.0).round() as u8
}
/// True when one of the 8 neighbours of `(x, y)` (inside a `w` x `h` area) is in the region.
fn touches_region(x: usize, y: usize, w: usize, h: usize, selected: impl Fn(usize, usize) -> bool) -> bool {
(-1i32..=1).any(|dy| {
(-1i32..=1).any(|dx| {
let (nx, ny) = (x as i32 + dx, y as i32 + dy);
(dx, dy) != (0, 0) && nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && selected(nx as usize, ny as usize)
})
})
}
/// Straight RGBA8 copy of `area` of a surface, read in parallel bands on native.
pub fn rgba8_image(s: &Surface, area: Rect) -> Vec<[u8; 4]> {
let (w, h) = (area.width() as usize, area.height() as usize);
@@ -266,10 +299,62 @@ impl Region {
}
}
/// How a wand-style fill measures how far an 8-bit colour is from the clicked one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorDistance {
/// The largest difference in any one of R, G and B.
LargestChannel,
/// The spread of `{0, dR, dG, dB}`: changes in the same direction count once, opposite
/// changes add up. Only opaque colours were measured, so a partly transparent seed or pixel
/// uses [`Self::LargestChannel`].
Spread,
}
impl ColorDistance {
fn rgb(self, p: [u8; 4], seed: [u8; 4]) -> i32 {
let d = [0, 1, 2].map(|c| p[c] as i32 - seed[c] as i32);
match self {
Self::Spread if p[3] == 255 && seed[3] == 255 => d.iter().fold(0, |m, v| m.max(*v)) - d.iter().fold(0, |m, v| m.min(*v)),
Self::LargestChannel | Self::Spread => d.iter().fold(0, |m, v| m.max(v.abs())),
}
}
}
/// Magic wand on 8-bit pixels: a scanline flood fill (or a global match) that only allocates a
/// byte mark per pixel, then anti-aliases just the edges inside the touched bounding box.
/// Matches [`magic_wand`] for 8-bit sources. `None` if the seed is outside `area`.
pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option<Region> {
wand_region_within(img, area, seed, tolerance, contiguous, anti_alias, None)
}
/// [`wand_region`] whose contiguous fill only passes through pixels at least half selected in
/// `within` (the current selection's coverage over `area`, row-major): Subtract and Intersect
/// grow the region from the seed through the selection only (#11779). A seed outside it finds
/// nothing. A global match (`contiguous` off) ignores `within`.
pub fn wand_region_within(
img: &[[u8; 4]],
area: Rect,
seed: (i32, i32),
tolerance: f32,
contiguous: bool,
anti_alias: bool,
within: Option<&[f32]>,
) -> Option<Region> {
wand_region_by(img, area, seed, tolerance, contiguous, anti_alias, within, ColorDistance::LargestChannel)
}
/// [`wand_region_within`] measuring how far a colour is from the clicked one with `distance`.
#[allow(clippy::too_many_arguments)]
pub fn wand_region_by(
img: &[[u8; 4]],
area: Rect,
seed: (i32, i32),
tolerance: f32,
contiguous: bool,
anti_alias: bool,
within: Option<&[f32]>,
distance: ColorDistance,
) -> Option<Region> {
if !area.contains(seed.0, seed.1) {
return None;
}
@@ -277,11 +362,16 @@ pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32
if w.checked_mul(h).is_none_or(|n| n > img.len()) {
return None;
}
let within = within.filter(|_| contiguous).filter(|m| m.len() >= w * h);
let inside = |i: usize| within.is_none_or(|m| m.get(i).is_some_and(|v| *v >= 0.5));
if !inside((seed.1 - area.y0) as usize * w + (seed.0 - area.x0) as usize) {
return None;
}
let target = img[(seed.1 - area.y0) as usize * w + (seed.0 - area.x0) as usize];
let tol = (tolerance + 1e-3).floor().max(0.0) as i32;
// Copying a selection can leave RGB under zero alpha. Those invisible colours must not
// split a transparent region into pieces, as if the copied source were still visible.
let similar = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (0..4).all(|c| (p[c] as i32 - target[c] as i32).abs() <= tol);
let similar = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (distance.rgb(p, target) <= tol && (p[3] as i32 - target[3] as i32).abs() <= tol);
let mut marks = vec![0u8; w * h];
let (mut bx0, mut by0, mut bx1, mut by1) = (usize::MAX, usize::MAX, 0usize, 0usize);
if contiguous {
@@ -293,10 +383,10 @@ pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32
continue;
}
let (mut l, mut r) = (x, x);
while l > 0 && marks[row + l - 1] == 0 && similar(img[row + l - 1]) {
while l > 0 && marks[row + l - 1] == 0 && similar(img[row + l - 1]) && inside(row + l - 1) {
l -= 1;
}
while r + 1 < w && marks[row + r + 1] == 0 && similar(img[row + r + 1]) {
while r + 1 < w && marks[row + r + 1] == 0 && similar(img[row + r + 1]) && inside(row + r + 1) {
r += 1;
}
marks[row + l..=row + r].fill(255);
@@ -308,7 +398,7 @@ pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32
let nrow = ny * w;
let mut in_run = false;
for nx in l..=r {
let ok = marks[nrow + nx] == 0 && similar(img[nrow + nx]);
let ok = marks[nrow + nx] == 0 && similar(img[nrow + nx]) && inside(nrow + nx);
if ok && !in_run {
stack.push((nx, ny));
}
@@ -356,25 +446,11 @@ pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32
let x = x0 + xx;
let v = at(x, y);
*o = v;
if !anti_alias {
continue;
}
// Same rule as `antialias`: edge pixels blend with their 3×3 neighbourhood; neighbours
// outside the area count as the pixel itself.
let mut sum = 0u32;
let mut edge = false;
for dy in -1i32..=1 {
for dx in -1i32..=1 {
let (nx, ny) = (x as i32 + dx, y as i32 + dy);
let n = if nx < 0 || ny < 0 || nx >= w as i32 || ny >= h as i32 { v } else { at(nx as usize, ny as usize) };
edge |= n != v;
sum += n as u32;
}
}
if edge {
let avg = sum as f32 / (9.0 * 255.0);
let f = if v > 127 { 0.5 + 0.5 * avg } else { 0.5 * avg };
*o = (f * 255.0).round() as u8;
// Same rule as `magic_wand`: the region stays fully selected; a pixel just outside
// it gets a fringe by how far its colour is past the tolerance.
if anti_alias && v == 0 && touches_region(x, y, w, h, |nx, ny| at(nx, ny) != 0) {
let p = img[y * w + x];
*o = fringe_coverage((distance.rgb(p, target) - tol) as f32, f32::from(p[3].min(target[3])));
}
}
};
@@ -435,32 +511,6 @@ pub fn combine_region(old: Option<&Surface>, new: Option<&Region>, mode: Selecti
}
}
/// Softens hard mask edges: edge pixels become the 3×3 average.
fn antialias(m: &mut [f32], w: usize, h: usize) {
let src = m.to_vec();
for y in 0..h {
for x in 0..w {
let i = y * w + x;
let mut sum = 0.0;
let mut cnt = 0.0;
let mut edge = false;
for dy in -1i32..=1 {
for dx in -1i32..=1 {
let (xx, yy) = (x as i32 + dx, y as i32 + dy);
let v = if xx < 0 || yy < 0 || xx >= w as i32 || yy >= h as i32 { src[i] } else { src[yy as usize * w + xx as usize] };
edge |= v != src[i];
sum += v;
cnt += 1.0;
}
}
if edge {
// Keep selected pixels mostly selected, add a soft fringe.
m[i] = if src[i] > 0.5 { 0.5 + 0.5 * sum / cnt } else { 0.5 * sum / cnt };
}
}
}
}
/// Colour Range: coverage falls off linearly with the per-channel colour
/// distance; `fuzziness` in levels (0–200).
pub fn color_range(px: &[[f32; 4]], color: [f32; 3], fuzziness: f32) -> Vec<f32> {
@@ -780,10 +830,13 @@ pub fn tone_range(px: &[[f32; 4]], lo: f32, hi: f32, falloff: f32) -> Vec<f32> {
mod distance;
#[cfg(test)]
mod ellipse_aa_edge_tests;
mod inverse;
mod lasso;
mod marquee;
mod morphology;
#[cfg(test)]
mod wand_antialias_tests;
pub use distance::edt;
pub use inverse::inverse_surface;
+3 -1
View File
@@ -106,7 +106,9 @@ fn wand_contiguous_vs_global() {
let g = magic_wand(&px, a, (3, 3), 10.0, false, false);
assert_eq!(g.iter().filter(|v| **v > 0.0).count(), 80);
let aa = magic_wand(&px, a, (3, 3), 10.0, true, true);
assert!(aa[3 * 20 + 6] > 0.0 && aa[3 * 20 + 6] < 1.0);
// #11776: anti-aliasing keeps the region whole and adds no fringe next to a colour this far
// past the tolerance (white is 245 levels from red, beyond the fringe's fade).
assert_eq!((aa[3 * 20 + 5], aa[3 * 20 + 6]), (1.0, 0.0));
assert!(magic_wand(&px, a, (50, 3), 10.0, true, false).iter().all(|v| *v == 0.0));
}
@@ -0,0 +1,128 @@
//! The Magic Wand's Anti-alias against the reference measurement (#11776): the region itself
//! stays fully selected, and a one-pixel soft fringe lies only outside it, next to colours just
//! past the tolerance. Document 800 x 600: a solid red rectangle 100,100–300,250 on a transparent
//! layer, and a grey ramp of ten 40 px blocks (grey 100, 105, …, 145) from x 100 at y 350–450,
//! on its own transparent layer or composited on white (Sample All Layers).
use photocraft_geom::Rect;
use super::{Region, magic_wand, wand_region};
const AREA: Rect = Rect { x0: 0, y0: 0, x1: 800, y1: 600 };
const W: usize = 800;
const H: usize = 600;
fn red_rectangle() -> Vec<[u8; 4]> {
let mut img = vec![[0u8; 4]; W * H];
for y in 100..250 {
for x in 100..300 {
img[y * W + x] = [220, 30, 30, 255];
}
}
img
}
/// The grey ramp at y 350–450 on a transparent layer, or on white when `on_white`.
fn ramp(on_white: bool) -> Vec<[u8; 4]> {
let mut img = vec![if on_white { [255u8; 4] } else { [0u8; 4] }; W * H];
for y in 350..450 {
for b in 0..10u8 {
let g = 100 + 5 * b;
for x in 100 + 40 * b as usize..140 + 40 * b as usize {
img[y * W + x] = [g, g, g, 255];
}
}
}
img
}
/// (bounds of every touched pixel, fully selected count, partly selected count).
fn stats(r: &Region) -> (Rect, usize, usize) {
let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);
let (mut full, mut part) = (0, 0);
for y in r.bbox.y0..r.bbox.y1 {
for x in r.bbox.x0..r.bbox.x1 {
let v = (r.at(x, y) * 255.0).round() as u8;
if v == 0 {
continue;
}
(x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1));
if v == 255 { full += 1 } else { part += 1 }
}
}
(Rect::new(x0, y0, x1, y1), full, part)
}
fn coverage(r: &Region, x: i32, y: i32) -> u8 {
(r.at(x, y) * 255.0).round() as u8
}
#[test]
fn a_shape_next_to_a_clearly_different_colour_gets_no_fringe() {
let img = red_rectangle();
for aa in [true, false] {
let r = wand_region(&img, AREA, (150, 150), 32.0, true, aa).unwrap();
assert_eq!(stats(&r), (Rect::new(100, 100, 300, 250), 30000, 0), "anti-alias {aa}");
}
}
#[test]
fn the_grey_ramp_gets_one_nearly_selected_column_past_the_tolerance() {
let img = ramp(false);
// Tolerance 32 from grey 100: blocks 100 to 130 (x 100–380) fully selected; the 135 block
// is 3 levels past it, so its first column is nearly selected.
let r = wand_region(&img, AREA, (110, 400), 32.0, true, true).unwrap();
let (bounds, full, part) = stats(&r);
assert_eq!((full, part), (280 * 100, 100), "{bounds:?}");
assert_eq!(bounds, Rect::new(100, 350, 381, 450));
for y in [350, 400, 449] {
assert_eq!(coverage(&r, 379, y), 255, "the region's last column stays fully selected");
assert_eq!(coverage(&r, 380, y), 251, "one fringe column of the next block, as measured");
assert_eq!(coverage(&r, 381, y), 0, "only one column");
}
// Transparent pixels above and below the ramp have no colour: no fringe there.
assert_eq!(coverage(&r, 200, 349), 0);
assert_eq!(coverage(&r, 200, 450), 0);
// Tolerance 10: x 100–220 plus one partly selected column of the 115 block.
let r = wand_region(&img, AREA, (110, 400), 10.0, true, true).unwrap();
let (bounds, full, part) = stats(&r);
assert_eq!((bounds, full, part), (Rect::new(100, 350, 221, 450), 120 * 100, 100));
assert_eq!(coverage(&r, 220, 400), 249, "5 levels past tolerance 10, as measured");
}
#[test]
fn anti_alias_off_has_no_partly_selected_pixels() {
let img = ramp(false);
let r = wand_region(&img, AREA, (110, 400), 32.0, true, false).unwrap();
assert_eq!(stats(&r), (Rect::new(100, 350, 380, 450), 28000, 0));
}
#[test]
fn the_8_bit_and_f32_wands_draw_the_same_fringe() {
let img = ramp(false);
let f: Vec<[f32; 4]> = img.iter().map(|p| p.map(|v| f32::from(v) / 255.0)).collect();
for (tol, contiguous) in [(32.0, true), (10.0, true), (32.0, false)] {
let r = wand_region(&img, AREA, (110, 400), tol, contiguous, true).unwrap();
let m = magic_wand(&f, AREA, (110, 400), tol, contiguous, true);
for y in 340..460 {
for x in 90..520 {
let want = (m[y as usize * W + x as usize] * 255.0).round() as u8;
assert_eq!(coverage(&r, x, y), want, "tolerance {tol}, contiguous {contiguous} at {x},{y}");
}
}
}
}
#[test]
fn on_the_composite_the_white_around_the_ramp_gets_the_measured_fringe() {
// Sample All Layers: the ramp on white. White is 155 levels from grey 100, 123 past
// tolerance 32; the reference application's fringe there reads 110 (Photoshop 2025, the
// same points; the issue reports 131–177 around the ramp).
let img = ramp(true);
let r = wand_region(&img, AREA, (110, 400), 32.0, true, true).unwrap();
for (x, y) in [(200, 349), (200, 450), (99, 400), (99, 349)] {
assert_eq!(coverage(&r, x, y), 110, "{x},{y}");
}
assert_eq!(coverage(&r, 380, 400), 251, "the near-miss block still gets the stronger fringe");
assert_eq!(coverage(&r, 200, 400), 255, "inside stays fully selected");
}
+66
View File
@@ -218,6 +218,72 @@ pub fn quad_size(q: &[[f64; 2]; 4]) -> (f64, f64) {
((len(tl, tr) + len(bl, br)) / 2.0, (len(tl, bl) + len(tr, br)) / 2.0)
}
/// How much the depth must change across the quad, as a fraction, for a pair of sides to count as
/// converging. Below this the recovered proportions are dominated by a pixel of click error.
const MIN_FORESHORTENING: f64 = 0.005;
/// How many times larger or smaller than the quad's longest edge an estimated side may be.
const MAX_ESTIMATE_RATIO: f64 = 4.0;
/// How far, as a fraction, one pixel of error on one corner may move the recovered proportions.
/// Quads from a camera model move about 1 %; the issue's measured skewed quad moves 5.3 %.
const MAX_ASPECT_SWING: f64 = 0.1;
/// The free output size of a Perspective Crop of `q` (TL, TR, BR, BL) in an image centred on
/// `center`: the rectangle the quad shows in perspective, or the quad's longest edges when its
/// sides are too close to parallel to recover that, the estimate would not survive a pixel of
/// click error, or it is implausible.
pub fn quad_free_size(q: &[[f64; 2]; 4], center: [f64; 2]) -> (f64, f64) {
let len = |a: [f64; 2], b: [f64; 2]| (b[0] - a[0]).hypot(b[1] - a[1]);
let [tl, tr, br, bl] = *q;
let (edge_w, edge_h) = (len(tl, tr).max(len(bl, br)), len(tl, bl).max(len(tr, br)));
let near = |v: f64, edge: f64| v.is_finite() && v >= edge / MAX_ESTIMATE_RATIO && v <= edge * MAX_ESTIMATE_RATIO;
match perspective_size(q, center) {
Some((w, h)) if near(w, edge_w) && near(h, edge_h) => (w, h),
_ => (edge_w, edge_h),
}
}
/// The size [`perspective_estimate`] gives `q`, or `None` when moving any corner one pixel along
/// either axis loses the estimate or swings its proportions by more than [`MAX_ASPECT_SWING`].
fn perspective_size(q: &[[f64; 2]; 4], center: [f64; 2]) -> Option<(f64, f64)> {
let (width, aspect) = perspective_estimate(q, center)?;
for corner in 0..4 {
for axis in 0..2 {
for step in [-1.0, 1.0] {
let mut nudged = *q;
nudged[corner][axis] += step;
let (_, other) = perspective_estimate(&nudged, center)?;
if (other / aspect - 1.0).abs() > MAX_ASPECT_SWING {
return None;
}
}
}
}
Some((width, width / aspect))
}
/// The width and the aspect ratio of the rectangle `q` shows. The width is the largest horizontal
/// scale at a corner of the unit-square-to-quad map, so the nearest part of the quad keeps its
/// detail. The aspect ratio is recovered with the principal point at `center` (Zhang and He,
/// "Whiteboard scanning and image enhancement", 2007). `None` when two sides are nearly parallel,
/// which leaves the focal length undefined.
fn perspective_estimate(q: &[[f64; 2]; 4], [cx, cy]: [f64; 2]) -> Option<(f64, f64)> {
let Homography([a, b, _, d, e, _, g, h, _]) = Homography::rect_to_quad([0.0, 0.0, 1.0, 1.0], *q)?;
if g.abs().min(h.abs()) < MIN_FORESHORTENING {
return None;
}
let (ux, uy, vx, vy) = (a - g * cx, d - g * cy, b - h * cx, e - h * cy);
let focal2 = -(ux * vx + uy * vy) / (g * h);
if !focal2.is_finite() || focal2 <= 0.0 {
return None;
}
let focal = focal2.sqrt();
let aspect = ux.hypot(uy).hypot(g * focal) / vx.hypot(vy).hypot(h * focal);
let scale_at = |[s, t]: [f64; 2], [x, y]: [f64; 2]| (a - x * g).hypot(d - y * g) / (1.0 + g * s + h * t);
let [tl, tr, br, bl] = *q;
let width = [scale_at([0.0, 0.0], tl), scale_at([1.0, 0.0], tr), scale_at([1.0, 1.0], br), scale_at([0.0, 1.0], bl)].into_iter().fold(0.0, f64::max);
Some((width, aspect))
}
/// The homography taking the quad `q` (TL, TR, BR, BL) onto the rectangle (0, 0)–(`w`, `h`), corner
/// to corner: the inverse of the unit-square-to-quad map (Heckbert, "Fundamentals of Texture
/// Mapping and Image Warping", 1989, §2.2.3) scaled to the rectangle. `None` when `q` isn't a
+176 -17
View File
@@ -1,6 +1,6 @@
use super::content::{render_content, surface_to_buffer};
use super::ctx::Ctx;
use super::{BlendMode, Document, Layer, LayerContent, Rect, advanced, bounds, effects, masks, shape_split};
use super::{BlendMode, Document, Layer, LayerContent, Rect, adjustment_quantum, advanced, bounds, effects, masks, shape_split};
/// Bounds of a layer's own pixels (union over group children; the canvas
/// for fill layers; an artboard's board).
@@ -379,11 +379,16 @@ pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option<Rect> {
if !transparent_outside(layer) {
return None;
}
let m = if effects::has_effects(layer) { effects::margin(layer) } else { 0 };
let own = match &layer.content {
LayerContent::Group(g) if g.artboard.is_none() => {
let mut acc = frame_stroke_bounds(layer, canvas);
// A shapeless group's effects cover the whole layer: `layer_bounds` gives the canvas.
LayerContent::Group(g) if g.artboard.is_none() && !advanced::shapeless(layer) => {
// Children up to its effects' reach off the canvas still cast them onto it (group
// effects are built past the canvas).
let near = canvas.inflate(m);
let mut acc = frame_stroke_bounds(layer, near);
for c in g.children.iter().filter(|c| c.visible) {
let b = composite_bounds(c, canvas)?;
let b = composite_bounds(c, near)?;
if !b.is_empty() {
acc = if acc.is_empty() { b } else { acc.union(&b) };
}
@@ -396,7 +401,6 @@ pub fn composite_bounds(layer: &Layer, canvas: Rect) -> Option<Rect> {
if own.is_empty() {
return Some(Rect::EMPTY);
}
let m = if effects::has_effects(layer) { effects::margin(layer) } else { 0 };
Some(own.inflate(m).intersect(&canvas))
}
@@ -424,23 +428,47 @@ pub fn change_bounds(layer: &Layer, canvas: Rect) -> Option<Rect> {
composite_bounds(layer, canvas)
}
/// [`change_bounds`] of `layers[k]` in its sibling list (bottom→top), which also bounds a clipped
/// adjustment layer: it changes only its clip base's pixels, so it reaches as far as showing,
/// hiding or restyling that base does (#6535). Still `None` when there is no base below it (the
/// compositor then draws it as an ordinary adjustment) or the base is an adjustment itself
/// (layers clipped to one composite atop the adjusted backdrop, everywhere). `outer` is the list
/// holding the group whose children `layers` are, and that group's index there (`None` at the
/// top level): a pass-through group that is a clip base renders isolated while it holds a visible
/// adjustment, so showing or hiding one inside can change the whole group.
pub fn change_bounds_in(layers: &[Layer], k: usize, outer: Option<(&[Layer], usize)>, canvas: Rect) -> Option<Rect> {
/// The lists holding the groups around a sibling list, outermost first: each list, and the
/// group's index there (empty at the top level).
pub type Ancestors<'a> = [(&'a [Layer], usize)];
/// The union of two bounds, either of which may be empty.
fn join(a: Rect, b: Rect) -> Rect {
if a.is_empty() {
b
} else if b.is_empty() {
a
} else {
a.union(&b)
}
}
/// [`change_bounds`] of `layers[k]` in its sibling list (bottom→top), which also bounds:
/// - a clipped adjustment layer: it changes only its clip base's pixels, so it reaches as far as
/// showing, hiding or restyling that base does (#6535). Still `None` when there is no base below
/// it (the compositor then draws it as an ordinary adjustment) or the base is an adjustment
/// itself (layers clipped to one composite atop the adjusted backdrop, everywhere). A
/// pass-through group that is a clip base renders isolated while it holds a visible
/// adjustment, so showing or hiding one inside can change the whole group.
/// - an unclipped adjustment layer, and a pass-through group holding one (see
/// [`adjustment_reach`]).
///
/// `ancestors` are the lists holding the groups around `layers`, outermost first; `depth` is the
/// document's, which decides whether adjustments round the backdrop ([`adjustment_quantum`]).
///
/// The result is an **in-place** bound: what changes if the layer changes where it is. For an
/// adjustment it covers the layers beneath it (or its clip base), which don't move with it, so it
/// must never be translated, as a Move drag preview would. Use the context-free [`change_bounds`],
/// which moves with the layer, for that.
pub fn change_bounds_in(layers: &[Layer], k: usize, ancestors: &Ancestors, depth: photocraft_color::SampleType, canvas: Rect) -> Option<Rect> {
let layer = layers.get(k)?;
if layer.clipped && matches!(layer.content, LayerContent::Adjustment(_)) {
let base = layers.get(..k)?.iter().rev().find(|l| !l.clipped)?;
if matches!(base.content, LayerContent::Adjustment(_)) {
return None;
}
if let Some((outer, g)) = outer
&& let Some(group) = outer.get(g)
if let Some((outer, g)) = ancestors.last()
&& let Some(group) = outer.get(*g)
&& group.blend == BlendMode::PassThrough
&& !group.clipped
&& outer.get(g + 1).is_some_and(|above| above.clipped)
@@ -450,7 +478,138 @@ pub fn change_bounds_in(layers: &[Layer], k: usize, outer: Option<(&[Layer], usi
}
return change_bounds(base, canvas);
}
change_bounds(layer, canvas)
match &layer.content {
LayerContent::Adjustment(_) => adjustment_reach(layers, k, ancestors, depth, canvas),
LayerContent::Group(g) if layer.blend == BlendMode::PassThrough && !layer.clipped && change_bounds(layer, canvas).is_none() => {
// Its own pixels, plus where each adjustment inside reaches.
let mut acc = composite_bounds(layer, canvas)?;
let mut inner = ancestors.to_vec();
inner.push((layers, k));
for (j, c) in g.children.iter().enumerate() {
if matches!(c.content, LayerContent::Adjustment(_)) || matches!(c.content, LayerContent::Group(_)) && c.blend == BlendMode::PassThrough {
acc = join(acc, change_bounds_in(&g.children, j, &inner, depth, canvas)?);
}
}
Some(acc)
}
_ => change_bounds(layer, canvas),
}
}
/// Where showing, hiding or restyling the unclipped adjustment `layers[k]` can change the
/// document, or `None` for anywhere. It changes only pixels already drawn beneath it in its
/// isolation scope: the visible layers below it, and inside a pass-through group the layers below
/// the group too, up to the top level or the first isolated group (a pass-through group the
/// compositor isolates reaches less, so this still covers it). Adjustments draw no alpha of their
/// own, so what is transparent there stays so.
///
/// In a 32-bit document it also changes only where its layer mask lets it through (an enabled
/// mask that hides by default at full density, grown by the feather). An integer document rounds
/// the whole backdrop to its levels after every visible adjustment layer, masked or not (#9033),
/// so there the mask bounds nothing. Layers clipped to an adjustment composite atop the adjusted
/// backdrop wherever they draw, and a knockout reveals what lies beneath it: both stay `None`.
pub fn adjustment_reach(layers: &[Layer], k: usize, ancestors: &Ancestors, depth: photocraft_color::SampleType, canvas: Rect) -> Option<Rect> {
let layer = layers.get(k)?;
if layers.get(k + 1).is_some_and(|above| above.clipped) || layer.advanced.knockout != photocraft_doc::Knockout::None {
return None;
}
let mask = adjustment_quantum(depth).is_none().then(|| adjustment_mask_bounds(layer)).flatten();
let below = beneath(layers, k, ancestors, canvas);
let reach = match (mask, below) {
(Some(m), Some(b)) => m.intersect(&b).intersect(&canvas),
(Some(m), None) => m.intersect(&canvas),
(None, b) => b?,
};
// A pass-through group that is a clip base renders isolated while it holds a visible
// adjustment, so showing or hiding the last one switches how the whole group composites: the
// two agree outside `beneath` only up to float rounding. The clipped branch of
// [`change_bounds_in`] covers the group the same way.
if let Some((outer, g)) = ancestors.last()
&& let Some(group) = outer.get(*g)
&& group.blend == BlendMode::PassThrough
&& !group.clipped
&& outer.get(g + 1).is_some_and(|above| above.clipped)
{
return Some(join(reach, composite_bounds(group, canvas)?));
}
Some(reach)
}
/// Where an adjustment's layer mask can let it through: an enabled mask that hides by default at
/// full density, so outside its painted tiles (grown by its feather, or a vector mask's, since
/// the two multiply) it hides the layer.
fn adjustment_mask_bounds(layer: &Layer) -> Option<Rect> {
let m = layer.mask.as_ref().filter(|m| m.enabled && m.density >= 1.0)?;
if !m.surface.default_pixel().first().is_some_and(|v| *v <= 0.0) {
return None;
}
let vector = layer.vector_mask.as_ref().filter(|v| v.enabled).map_or(0.0, |v| photocraft_vector::feather::feather_sigma(v.feather));
let sigma = photocraft_vector::feather::feather_sigma(m.feather).max(vector);
let tiles = m.surface.tile_bounds();
Some(if sigma > 0.0 { photocraft_vector::feather::grow(tiles, sigma) } else { tiles })
}
/// The union of [`composite_bounds`] of the visible layers below `layers[k]`, continuing below a
/// pass-through group into the list holding it; `None` when any may draw anywhere.
fn beneath(layers: &[Layer], k: usize, ancestors: &Ancestors, canvas: Rect) -> Option<Rect> {
let mut acc = Rect::EMPTY;
for l in layers.get(..k)?.iter().filter(|l| l.visible) {
acc = join(acc, composite_bounds(l, canvas)?);
}
if let Some((&(outer, g), rest)) = ancestors.split_last()
&& let Some(group) = outer.get(g)
&& group.blend == BlendMode::PassThrough
{
if group.clipped {
return None;
}
// An artboard's background lies beneath its layers.
if let LayerContent::Group(gr) = &group.content
&& let Some(ab) = gr.artboard.as_ref().filter(|ab| ab.background.rgba().is_some())
{
acc = join(acc, ab.rect.intersect(&canvas));
}
acc = join(acc, beneath(outer, g, rest, canvas)?);
}
Some(acc)
}
/// Where a layer sits: its sibling list, its index there, and the lists around it ([`Ancestors`]).
pub type Placement<'a> = (&'a [Layer], usize, Vec<(&'a [Layer], usize)>);
/// Where layer `id` sits in `doc` ([`Placement`]).
pub fn siblings_of(doc: &Document, id: photocraft_doc::LayerId) -> Option<Placement<'_>> {
fn find<'a>(layers: &'a [Layer], id: photocraft_doc::LayerId, path: &mut Vec<(&'a [Layer], usize)>) -> Option<(&'a [Layer], usize)> {
for (k, l) in layers.iter().enumerate() {
if l.id == id {
return Some((layers, k));
}
if let Some(c) = l.children() {
path.push((layers, k));
if let Some(hit) = find(c, id, path) {
return Some(hit);
}
path.pop();
}
}
None
}
let mut path = Vec::new();
let (layers, k) = find(&doc.layers, id, &mut path)?;
Some((layers, k, path))
}
/// [`change_bounds_in`] of layer `id` where it sits in `doc`, grown by the reach of the effects
/// of the groups around it (a parent's drop shadow), or `None` for anywhere (or no such layer).
/// An in-place bound: never translate it (see [`change_bounds_in`]).
pub fn layer_change_bounds(doc: &Document, id: photocraft_doc::LayerId) -> Option<Rect> {
let (layers, k, ancestors) = siblings_of(doc, id)?;
let reach = ancestors.iter().filter_map(|(ls, g)| ls.get(*g)).filter(|l| effects::has_effects(l)).fold(0i32, |r, l| r.saturating_add(effects::margin(l)));
// Bounded within that reach of the canvas, not on it: a layer just off the canvas still
// moves a parent's shadow onto it (group effects are built past the canvas).
let canvas = doc.bounds();
let r = change_bounds_in(layers, k, &ancestors, doc.depth, canvas.inflate(reach))?;
Some(if r.is_empty() { r } else { r.inflate(reach).intersect(&canvas) })
}
/// Whether the layer's content is transparent outside its bounds (every surface it draws from
+2 -2
View File
@@ -65,8 +65,8 @@ use ctx::{Ctx, prepare_effects};
use ctx::{LayerKeys, PREPARE_DEPTH, effect_layers, prepare_tones};
use extents::mask_vals;
pub use extents::{
change_bounds, change_bounds_in, composite_bounds, effect_outline, effect_source_bounds, effects_frame, hard_shape_bounds, layer_bounds, paint_bounds,
relayout_damage, shape_bounds, soft_shape_frame, transparent_outside,
Ancestors, Placement, adjustment_reach, change_bounds, change_bounds_in, composite_bounds, effect_outline, effect_source_bounds, effects_frame,
hard_shape_bounds, layer_bounds, layer_change_bounds, paint_bounds, relayout_damage, shape_bounds, siblings_of, soft_shape_frame, transparent_outside,
};
#[cfg(test)]
use extents::{mask_k, shapeless_stroke_bounds, trim_to_painted};
+225 -11
View File
@@ -794,7 +794,7 @@ fn clipped_adjustment_changes_only_its_base() {
adj.clipped = true;
d.layers.push(adj);
assert_eq!(change_bounds(&d.layers[3], canvas), None);
assert_eq!(change_bounds_in(&d.layers, 3, None, canvas), Some(base_rect));
assert_eq!(change_bounds_in(&d.layers, 3, &[], SampleType::U8, canvas), Some(base_rect));
// Every pixel the toggle changes lies inside those bounds.
let shown = render(&d, canvas);
d.layers[3].visible = false;
@@ -810,24 +810,24 @@ fn clipped_adjustment_changes_only_its_base() {
}
assert_eq!(changed, base_rect);
// Other layers keep their own bounds.
assert_eq!(change_bounds_in(&d.layers, 2, None, canvas), Some(Rect::new(3, 2, 4, 3)));
assert_eq!(change_bounds_in(&d.layers, 9, None, canvas), None);
assert_eq!(change_bounds_in(&d.layers, 2, &[], SampleType::U8, canvas), Some(Rect::new(3, 2, 4, 3)));
assert_eq!(change_bounds_in(&d.layers, 9, &[], SampleType::U8, canvas), None);
// Unclipped, or with no base beneath it, it reaches everything.
let mut free = d.layers.clone();
free[3].clipped = false;
assert_eq!(change_bounds_in(&free, 3, None, canvas), None);
assert_eq!(change_bounds_in(&free, 3, &[], SampleType::U8, canvas), Some(canvas));
let orphan = vec![d.layers[3].clone()];
assert_eq!(change_bounds_in(&orphan, 0, None, canvas), None);
assert_eq!(change_bounds_in(&orphan, 0, &[], SampleType::U8, canvas), None);
// Clipped layers on an adjustment composite atop the adjusted backdrop.
let on_adj = vec![d.layers[0].clone(), Layer::new("lv", LayerContent::Adjustment(Adjustment::Invert)), d.layers[3].clone()];
assert_eq!(change_bounds_in(&on_adj, 2, None, canvas), None);
assert_eq!(change_bounds_in(&on_adj, 2, &[], SampleType::U8, canvas), None);
// A pass-through group holding an adjustment is isolated only while it has visible clipped
// layers, so they change whether its adjustment reaches the layers beneath.
let mut g = Layer::group("g", vec![solid_layer("in", base_rect, [0.2, 0.4, 0.6, 1.0]), Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]);
g.blend = BlendMode::PassThrough;
let on_group = vec![d.layers[0].clone(), g, d.layers[3].clone()];
assert_eq!(change_bounds_in(&on_group, 2, None, canvas), None);
assert_eq!(change_bounds_in(&on_group, 2, &[], SampleType::U8, canvas), None);
}
/// #6535: a clipped adjustment with no base beneath it, inside a pass-through group, composites
@@ -848,12 +848,12 @@ fn orphan_clipped_adjustment_in_pass_through_base_reaches_everything() {
let shown = px(&d, 0, 0);
d.layers[2].visible = false;
assert!(!close4(shown, px(&d, 0, 0)), "the toggle changes pixels outside the group");
assert_eq!(change_bounds_in(&d.layers, 2, None, canvas), None);
assert_eq!(change_bounds_in(&d.layers, 2, &[], SampleType::U8, canvas), None);
assert_eq!(change_bounds(&d.layers[1], canvas), None);
// With a base beneath it the clipped adjustment stays inside the group.
let LayerContent::Group(g) = &mut d.layers[1].content else { panic!("group") };
g.children.swap(0, 1);
assert_eq!(change_bounds_in(&d.layers, 2, None, canvas), Some(Rect::new(2, 1, 4, 3)));
assert_eq!(change_bounds_in(&d.layers, 2, &[], SampleType::U8, canvas), Some(Rect::new(2, 1, 4, 3)));
}
/// A pass-through group that is a clip base renders isolated while it holds a visible
@@ -880,11 +880,225 @@ fn clipped_adjustment_in_pass_through_clip_base_reaches_its_group() {
assert!(!close4(shown, px(&d, 7, 5)), "hiding A changes Q, outside A's base");
let group = Rect::new(2, 1, 8, 6);
let LayerContent::Group(g) = &d.layers[2].content else { panic!("group") };
assert_eq!(change_bounds_in(&g.children, 1, Some((&d.layers, 2)), canvas), Some(group));
assert_eq!(change_bounds_in(&g.children, 1, &[(&d.layers, 2)], SampleType::U8, canvas), Some(group));
// Not a clip base: the group stays pass-through either way, and A changes only its base.
d.layers.truncate(3);
let LayerContent::Group(g) = &d.layers[2].content else { panic!("group") };
assert_eq!(change_bounds_in(&g.children, 1, Some((&d.layers, 2)), canvas), Some(Rect::new(2, 1, 4, 3)));
assert_eq!(change_bounds_in(&g.children, 1, &[(&d.layers, 2)], SampleType::U8, canvas), Some(Rect::new(2, 1, 4, 3)));
}
/// The composite of `after` equals `before`'s outside `damage`, exactly (as the engine's
/// `unchanged_outside` oracle checks a step's damage).
fn unchanged_outside(before: &Document, after: &Document, damage: Rect) -> bool {
let (x, y) = (render(before, before.bounds()), render(after, after.bounds()));
let w = before.bounds().width() as i32;
x.px.iter().zip(&y.px).enumerate().all(|(i, (p, q))| p == q || damage.contains(i as i32 % w, i as i32 / w))
}
/// `d` with `layers[k]` (or, with `child`, that child of the group there) hidden.
fn hidden_at(d: &Document, k: usize, child: Option<usize>) -> Document {
let mut h = d.clone();
match child {
None => h.layers[k].visible = false,
Some(c) => h.layers[k].children_mut().unwrap()[c].visible = false,
}
h
}
/// An Invert adjustment whose layer mask reveals only `r`.
fn masked_invert(r: Rect) -> Layer {
let mut adj = Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert));
let mut m = LayerMask::hide_all();
m.surface.fill_rect(r, &[1.0]);
adj.mask = Some(m);
adj
}
/// A layer at 37 % opacity, so the backdrop it leaves falls between an integer document's
/// levels (which an adjustment above rounds away).
fn faint_layer(r: Rect) -> Layer {
let mut l = solid_layer("faint", r, [0.2, 0.4, 0.6, 1.0]);
l.opacity = 0.37;
l
}
/// #9329: in a 32-bit document a masked adjustment changes only under its mask (grown by its
/// feather), even over an opaque Background.
#[test]
fn a_masked_adjustment_changes_only_under_its_mask() {
let canvas = Rect::new(0, 0, 800, 600);
let reveal = Rect::new(520, 330, 560, 370);
for feather in [0.0, 6.0] {
let mut d = Document::with_background("t", Size::new(800, 600), ColorMode::Rgb, SampleType::F32, Color::WHITE);
d.layers.push(faint_layer(Rect::new(100, 100, 700, 500)));
let mut adj = masked_invert(reveal);
adj.mask.as_mut().unwrap().feather = feather;
d.layers.push(adj);
let b = change_bounds_in(&d.layers, 2, &[], SampleType::F32, canvas).expect("bounded by the mask");
assert!(b.contains_rect(&reveal) && b.width() < canvas.width() && b.height() < canvas.height(), "{b:?}");
let h = hidden_at(&d, 2, None);
assert_ne!(render(&d, canvas), render(&h, canvas));
assert!(unchanged_outside(&d, &h, b), "feather {feather}");
// At full density only: a lower density lets the adjustment through everywhere.
let mut thin = d.clone();
thin.layers[2].mask.as_mut().unwrap().density = 0.5;
assert_eq!(change_bounds_in(&thin.layers, 2, &[], SampleType::F32, canvas), Some(canvas));
}
}
/// #9329: with no Background, an unmasked adjustment reaches only the layers beneath it, in an
/// integer document too (rounding the backdrop leaves transparent pixels transparent).
#[test]
fn an_adjustment_over_small_layers_reaches_only_them() {
let canvas = Rect::new(0, 0, 40, 30);
let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8);
let (p, q) = (Rect::new(2, 3, 10, 9), Rect::new(20, 12, 30, 25));
d.layers.push(solid_layer("p", p, [0.2, 0.4, 0.6, 1.0]));
d.layers.push(faint_layer(q));
d.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)));
let k = d.layers.len() - 1;
let b = change_bounds_in(&d.layers, k, &[], SampleType::U8, canvas);
assert_eq!(b, Some(p.union(&q)));
let h = hidden_at(&d, k, None);
assert_ne!(render(&d, canvas), render(&h, canvas));
assert!(unchanged_outside(&d, &h, b.unwrap()));
}
/// #9329: over an opaque Background an adjustment reaches the canvas. In an integer document
/// even a masked one does: the backdrop is rounded to the document's levels after every visible
/// adjustment layer (#9033), outside its mask too.
#[test]
fn an_adjustment_over_a_background_reaches_the_canvas() {
let canvas = Rect::new(0, 0, 800, 600);
let reveal = Rect::new(520, 330, 560, 370);
let mut d = doc_white(800, 600);
d.layers.push(faint_layer(Rect::new(100, 100, 700, 500)));
d.layers.push(masked_invert(reveal));
assert_eq!(change_bounds_in(&d.layers, 2, &[], SampleType::U8, canvas), Some(canvas));
let h = hidden_at(&d, 2, None);
assert!(!unchanged_outside(&d, &h, reveal), "hiding it re-rounds pixels outside its mask");
let unmasked = {
let mut u = d.clone();
u.layers[2].mask = None;
u
};
assert_eq!(change_bounds_in(&unmasked.layers, 2, &[], SampleType::U8, canvas), Some(canvas));
assert_eq!(change_bounds_in(&unmasked.layers, 2, &[], SampleType::F32, canvas), Some(canvas));
}
/// #9329: inside a pass-through group an adjustment reaches the group's layers beneath it and
/// the layers beneath the group; so does the group itself.
#[test]
fn an_adjustment_in_a_pass_through_group_reaches_below_the_group() {
let canvas = Rect::new(0, 0, 40, 30);
let (p, q) = (Rect::new(2, 3, 10, 9), Rect::new(20, 12, 30, 25));
let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8);
d.layers.push(faint_layer(p));
let mut g = Layer::group("g", vec![solid_layer("q", q, [0.2, 0.4, 0.6, 1.0]), Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]);
g.blend = BlendMode::PassThrough;
d.layers.push(g);
let LayerContent::Group(gc) = &d.layers[1].content else { panic!("group") };
let b = change_bounds_in(&gc.children, 1, &[(&d.layers, 1)], SampleType::U8, canvas);
assert_eq!(b, Some(p.union(&q)));
let h = hidden_at(&d, 1, Some(1));
assert_ne!(render(&d, canvas), render(&h, canvas));
assert!(unchanged_outside(&d, &h, b.unwrap()));
// The group: its own pixels and its adjustment's reach.
assert_eq!(change_bounds(&d.layers[1], canvas), None);
let gb = change_bounds_in(&d.layers, 1, &[], SampleType::U8, canvas);
assert_eq!(gb, Some(p.union(&q)));
assert!(unchanged_outside(&d, &hidden_at(&d, 1, None), gb.unwrap()));
}
/// #9329: inside an isolated (Normal) group an adjustment reaches only the group's layers
/// beneath it.
#[test]
fn an_adjustment_in_an_isolated_group_stops_at_the_group() {
let canvas = Rect::new(0, 0, 40, 30);
let (p, q) = (Rect::new(2, 3, 10, 9), Rect::new(20, 12, 30, 25));
let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8);
d.layers.push(faint_layer(p));
let mut g = Layer::group("g", vec![faint_layer(q), Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]);
g.blend = BlendMode::Normal;
d.layers.push(g);
let LayerContent::Group(gc) = &d.layers[1].content else { panic!("group") };
let b = change_bounds_in(&gc.children, 1, &[(&d.layers, 1)], SampleType::U8, canvas);
assert_eq!(b, Some(q));
let h = hidden_at(&d, 1, Some(1));
assert_ne!(render(&d, canvas), render(&h, canvas));
assert!(unchanged_outside(&d, &h, q));
}
/// #9329: inside a pass-through artboard an adjustment also reaches the artboard's background,
/// which lies beneath its layers.
#[test]
fn an_adjustment_in_a_pass_through_artboard_reaches_its_background() {
let canvas = Rect::new(0, 0, 40, 30);
let board = Rect::new(4, 3, 24, 20);
let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8);
let mut ab = Layer::group("board", vec![Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]);
let LayerContent::Group(g) = &mut ab.content else { panic!("group") };
g.artboard = Some(photocraft_doc::Artboard::new(board));
d.layers.push(ab);
let LayerContent::Group(gc) = &d.layers[0].content else { panic!("group") };
let b = change_bounds_in(&gc.children, 0, &[(&d.layers, 0)], SampleType::U8, canvas);
assert_eq!(b, Some(board));
let h = hidden_at(&d, 0, Some(0));
assert_ne!(render(&d, canvas), render(&h, canvas));
assert!(unchanged_outside(&d, &h, board));
}
/// A layer just off the left edge of a 40 × 30 canvas, in a group whose drop shadow reaches
/// onto it.
fn shadowed_group_off_the_canvas() -> Layer {
let mut g = Layer::group("g", vec![solid_layer("off", Rect::new(-6, 8, -1, 16), [0.2, 0.4, 0.6, 1.0])]);
g.effects.items.push(Effect::default_drop_shadow());
g
}
/// #9329: an adjustment above a group whose pixels lie just off the canvas reaches the group's
/// drop shadow on the canvas.
#[test]
fn an_adjustment_over_a_shadowed_group_off_the_canvas_reaches_the_shadow() {
let canvas = Rect::new(0, 0, 40, 30);
let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8);
d.layers.push(shadowed_group_off_the_canvas());
d.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)));
let b = change_bounds_in(&d.layers, 1, &[], SampleType::U8, canvas).expect("bounded");
let h = hidden_at(&d, 1, None);
assert_ne!(render(&d, canvas), render(&h, canvas), "the shadow reaches the canvas");
assert!(unchanged_outside(&d, &h, b), "{b:?}");
}
/// #9329: a layer just off the canvas in a group with a drop shadow changes the shadow on the
/// canvas: [`layer_change_bounds`] grows by the reach of the groups around it.
#[test]
fn a_layer_off_the_canvas_in_a_shadowed_group_bounds_the_shadow() {
let canvas = Rect::new(0, 0, 40, 30);
let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8);
d.layers.push(shadowed_group_off_the_canvas());
let id = d.layers[0].children().unwrap()[0].id;
let b = layer_change_bounds(&d, id).expect("bounded");
let h = hidden_at(&d, 0, Some(0));
assert_ne!(render(&d, canvas), render(&h, canvas), "the shadow reaches the canvas");
assert!(unchanged_outside(&d, &h, b), "{b:?}");
}
/// #9329: a group with Transparency Shapes Layer off takes the whole layer as its effects'
/// shape, so it draws over the whole canvas, also while it holds an adjustment.
#[test]
fn a_shapeless_group_holding_an_adjustment_reaches_the_canvas() {
let canvas = Rect::new(0, 0, 40, 30);
let q = Rect::new(20, 12, 30, 25);
let mut d = Document::new("t", Size::new(40, 30), ColorMode::Rgb, SampleType::U8);
let mut g = Layer::group("g", vec![solid_layer("q", q, [0.2, 0.4, 0.6, 1.0]), Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]);
g.effects.items.push(Effect::ColorOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), color: Color::BLACK });
g.advanced.transparency_shapes = false;
d.layers.push(g);
let h = hidden_at(&d, 0, None);
assert!(!unchanged_outside(&d, &h, q.inflate(effects::margin(&d.layers[0]))), "the overlay draws past its layers");
assert_eq!(composite_bounds(&d.layers[0], canvas), Some(canvas));
assert_eq!(change_bounds_in(&d.layers, 0, &[], SampleType::U8, canvas), Some(canvas));
}
#[test]
@@ -0,0 +1,71 @@
//! #11897: the Brush's chosen Clear on the Background paints as Normal. The options bar turns
//! Clear off at the press there (`clear_off_on_background` in ui-egui), so the engine never sees
//! it; a `"mode": "clear"` stroke that does reach the Background is a held `~`, which keeps
//! erasing to the background colour. On a pixel layer Clear still erases, and the Eraser on the
//! Background still paints the background colour.
use crate::Session;
use serde_json::{Value, json};
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap();
s.tools.foreground = BLACK;
s.tools.background = GREEN;
s
}
fn pixel(s: &mut Session, x: i32, y: i32) -> [f32; 4] {
let v = s.execute("document.pixel", json!({"x": x, "y": y})).unwrap();
let a: Vec<f32> = v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap() as f32).collect();
[a[0], a[1], a[2], a[3]]
}
fn close(a: [f32; 4], b: [f32; 4]) -> bool {
a.iter().zip(&b).all(|(x, y)| (x - y).abs() <= 0.02)
}
/// A hard stroke across (10..30, 10), as the canvas sends it in Clear mode.
fn clear_stroke() -> Value {
json!({"points": [[10, 10], [30, 10]], "size": 8, "hardness": 1.0, "erase": true, "mode": "clear"})
}
/// A held `~` on the Background erases to the background colour, as before #11897.
#[test]
fn a_clear_stroke_on_the_background_still_paints_the_background_colour() {
let mut s = session();
s.execute("paint.stroke", clear_stroke()).unwrap();
let p = pixel(&mut s, 20, 10);
assert!(close(p, GREEN), "painted {p:?}, not the foreground");
assert_eq!(s.active().unwrap().history.undo_label(), Some("Brush Tool"));
}
#[test]
fn a_normal_stroke_on_the_background_paints_the_foreground() {
let mut s = session();
s.execute("paint.stroke", json!({"points": [[10, 10], [30, 10]], "size": 8, "hardness": 1.0})).unwrap();
let p = pixel(&mut s, 20, 10);
assert!(close(p, BLACK), "{p:?}");
}
#[test]
fn clear_on_a_pixel_layer_still_erases() {
let mut s = session();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": [1.0, 0.0, 0.0, 1.0]})).unwrap();
s.execute("paint.stroke", clear_stroke()).unwrap();
let p = pixel(&mut s, 20, 10);
assert!(close(p, WHITE), "erased down to the white Background: {p:?}");
}
#[test]
fn the_eraser_on_the_background_still_paints_the_background_colour() {
let mut s = session();
s.execute("paint.stroke", json!({"points": [[10, 10], [30, 10]], "size": 8, "hardness": 1.0, "erase": true})).unwrap();
let p = pixel(&mut s, 20, 10);
assert!(close(p, GREEN), "{p:?}");
}
+19 -1
View File
@@ -242,9 +242,27 @@ pub(crate) fn transform_doc_marks(doc: &mut Document, a: &Affine) {
if let Some(wp) = &mut doc.work_path {
*wp = wp.transform(a);
}
// A note's icon point maps with the pixels; its popup keeps its size (#11795). Under Image Size
// and Canvas Size it also keeps its offset from the icon, as Photoshop's does. Where it sits
// after a turn or flip wasn't measured, so it keeps today's origin there: the top-left of the
// mapped rectangle.
for n in &mut doc.notes {
// An all-zero popup means none is stored (PSD export writes its default one): keep it.
if n.popup == [0.0; 4] {
n.position = map_pt(a, n.position);
continue;
}
let [px, py] = n.position;
let (dx, dy, w, h) = (n.popup[0] - px, n.popup[1] - py, n.popup[2] - n.popup[0], n.popup[3] - n.popup[1]);
n.position = map_pt(a, n.position);
n.popup = map_box(a, n.popup);
let [m0, m1, m2, m3, ..] = a.m;
let [x, y] = if m1.abs() < EPS && m2.abs() < EPS && m0 > 0.0 && m3 > 0.0 {
[n.position[0] + dx, n.position[1] + dy]
} else {
let [l, t, ..] = map_box(a, n.popup);
[l, t]
};
n.popup = [x, y, x + w, y + h];
}
for g in &mut doc.measurement.count_groups {
for p in &mut g.points {
+21 -4
View File
@@ -69,6 +69,10 @@ pub mod comps_cmds;
pub mod contour_lib_cmds;
#[cfg(test)]
mod count_delete_group_tests;
#[cfg(test)]
mod count_history_names_tests;
#[cfg(test)]
mod count_record_label_tests;
pub mod cutout_cmds;
pub mod distort_cmds;
pub mod document_preset_cmds;
@@ -98,6 +102,7 @@ pub mod history_select_cmds;
pub mod history_source_cmds;
pub mod image_cmds;
pub mod layer_copy_cmds;
pub mod layer_css_cmds;
pub mod layer_label_cmds;
pub mod layer_list_cmds;
pub mod layer_mask_props_cmds;
@@ -114,6 +119,8 @@ pub(super) mod migrate_cmds;
pub mod mode_cmds;
pub mod multichannel_cmds;
pub mod notes_cmds;
#[cfg(test)]
mod notes_stored_values_tests;
mod ops;
pub mod paint_cmds;
mod params;
@@ -150,6 +157,8 @@ pub mod type_area_cmds;
pub mod type_caret_cmds;
pub mod type_cmds;
pub mod type_extra_cmds;
#[cfg(test)]
mod type_indexed_mode_tests;
pub mod type_mask_cmds;
pub mod type_spell_cmds;
pub mod type_styles_cmds;
@@ -199,9 +208,14 @@ pub fn list_entry(s: &Session, c: &CommandSpec, reason: Option<String>) -> Value
/// Other names a command is looked for by, beyond its id and label: the Photoshop tools and
/// options it stands for (#5060). `select.rect` is also the Elliptical and Single Row/Column
/// Marquee, which an agent searches for as "ellipse" or "marquee".
pub(crate) const SEARCH_KEYWORDS: &[(&str, &str)] =
&[("select.rect", "Rectangular Marquee, Elliptical Marquee (\"ellipse\":true), ellipse, oval, circle, Single Row/Column Marquee (\"line\")")];
/// Marquee, which an agent searches for as "ellipse" or "marquee". The RAW Develop filter and
/// RAW Defaults keep Photoshop's "Camera Raw" name as a search alias only: the menus and windows
/// say "RAW Develop" (#12403).
pub(crate) const SEARCH_KEYWORDS: &[(&str, &str)] = &[
("select.rect", "Rectangular Marquee, Elliptical Marquee (\"ellipse\":true), ellipse, oval, circle, Single Row/Column Marquee (\"line\")"),
("filter.cameraRaw", "Camera Raw Filter"),
("edit.preferences.rawDefaults", "Camera Raw Defaults"),
];
/// [`SEARCH_KEYWORDS`] of command `id`, if it has any.
pub fn search_keywords(id: &str) -> Option<&'static str> {
@@ -573,6 +587,7 @@ fn build() -> Vec<CommandSpec> {
let add_copy = layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true);
// The dialog offers Duplicate Layer's own name: only a different one was typed (#9023).
let mut typed = None;
let mut shift = (0, 0);
let nid = s.edit("Duplicate Layer", |doc, active| {
let mut dup = layer_copy(doc, id, add_copy)?;
if let Some(name) = name.as_ref().filter(|n| **n != dup.name) {
@@ -583,11 +598,12 @@ fn build() -> Vec<CommandSpec> {
// A lone copy joins its original's link group, as in the reference application (#11217).
crate::layer_multi_cmds::relink_copies(doc, &[nid])?;
if !in_place {
crate::artboard_cmds::place_copy(doc, nid)?;
shift = crate::artboard_cmds::place_copy(doc, nid)?;
}
*active = Some(nid);
Ok(nid)
})?;
crate::artboard_cmds::follow_shift(s, shift);
if let Some(name) = typed {
crate::type_cmds::note_typed_name(s, nid, &name);
}
@@ -1389,6 +1405,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::adjust_cmds::specs());
v.extend(crate::layer_menu_cmds::specs());
v.extend(crate::layer_label_cmds::specs());
v.extend(crate::layer_css_cmds::specs());
v.extend(crate::layer_xmp_cmds::specs());
v.extend(crate::mode_cmds::specs());
v.extend(crate::multichannel_cmds::specs());
+14 -5
View File
@@ -334,11 +334,11 @@ fn record_drops_the_steps_of_a_command_that_failed_and_was_taken_back() {
assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 0, "no Duplicate step for a copy that was taken back");
// Straighten rolls back when its crop is refused after the rotation ran.
ruled_background(&mut s, 8);
ruled_layer(&mut s, 8);
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
s.authorize = Some(|id, _| if id == "image.crop" { Err(EngineError::Other("refused".into())) } else { Ok(()) });
s.execute("actions.record", json!({"name": "Refused"})).unwrap();
assert!(s.execute("image.analysis.straightenLayer", json!({})).is_err());
assert!(s.execute("image.analysis.straightenLayer", json!({"crop": true})).is_err());
assert_eq!(s.active().unwrap().doc.size.width, 80, "the rotation was taken back");
assert_eq!(s.execute("actions.stop", json!({})).unwrap()["steps"], 0, "no rotation step for a rotation that was taken back");
}
@@ -500,23 +500,32 @@ fn ruled_background(s: &mut Session, depth: u32) {
.unwrap();
}
/// The same, with a pixel layer on top: since #12033 the Background alone greys Straighten Layer
/// out, so the tests that run the command target a layer and pass `crop` explicitly.
fn ruled_layer(s: &mut Session, depth: u32) {
ruled_background(s, depth);
s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap();
}
#[test]
fn record_command_that_runs_commands_replays_it_once() {
// Straighten Layer runs Image Rotation and Crop itself: only its own call is recorded,
// so playback rotates once, not three times (rotate, crop, then straighten again).
for depth in [8, 16] {
let mut s = Session::new();
ruled_background(&mut s, depth);
ruled_layer(&mut s, depth);
s.execute("actions.record", json!({"name": "Level"})).unwrap();
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
s.execute("image.analysis.straightenLayer", json!({})).unwrap();
// #12033: the crop is asked for, as automation does; the Background it used to default to
// now greys the command out.
s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap();
s.execute("actions.stop", json!({})).unwrap();
let got = s.execute("actions.get", json!({"action": "Level"})).unwrap();
let ids: Vec<&str> = got["steps"].as_array().unwrap().iter().map(|st| st[0].as_str().unwrap()).collect();
assert_eq!(ids, ["image.analysis.rulerTool", "image.analysis.straightenLayer"], "depth {depth}");
let direct = s.active().unwrap().doc.clone();
ruled_background(&mut s, depth);
ruled_layer(&mut s, depth);
let before = s.active().unwrap().history.past_len();
let played = s.execute("actions.play", json!({"action": "Level"})).unwrap();
assert!(played.get("failed").is_none(), "depth {depth}: {played}");
+99 -11
View File
@@ -13,6 +13,11 @@
//! values the luminosity (0.30 R + 0.59 G + 0.11 B) of the composite in the document's value
//! range (0–255 at 8 bits, 0–32768 at 16 bits, 0–1 at 32 bits), integrated density area × mean.
//! Lengths and areas are scaled by the measurement scale.
//!
//! Straighten Layer is offered where the reference application offers it: the ruler line is needed,
//! and the target must be a single layer that is not the Background, not a group and not locked in
//! place ([`straighten_disabled`], #12033). A hidden target layer keeps the button and is refused
//! with [`STRAIGHTEN_HIDDEN_ERROR`] before anything changes.
use std::sync::Arc;
@@ -138,6 +143,60 @@ fn has_ruler(s: &Session) -> std::result::Result<(), String> {
s.active().and_then(|d| d.doc.measurement.ruler).map(|_| ()).ok_or_else(|| "no ruler line".into())
}
/// The reference's alert for Straighten Layer on a hidden target layer (#12033), measured: one
/// alert window with an OK button, and the document and its History stay as they were. The button
/// is *enabled* for a hidden layer, so this is the command's refusal and not a greyed state; the
/// options bar shows the same text through `tl!` (English is the catalog source).
pub const STRAIGHTEN_HIDDEN_ERROR: &str = "Could not straighten the layer because the target layer is hidden.";
/// The enabled check of `image.analysis.straightenLayer`: a ruler line, and a target the reference
/// straightens ([`straighten_disabled`], #12033).
fn has_straightenable_layer(s: &Session) -> std::result::Result<(), String> {
has_ruler(s)?;
straighten_disabled(s).map_or(Ok(()), |why| Err(why.into()))
}
/// Why Straighten Layer is greyed out for the current target, `None` when its button is live
/// (#12033). Measured with a ruler line drawn: the Background, two or more selected layers, a
/// group, a layer with Lock All and a layer with Lock Position all grey it out.
///
/// Deliberately not here: a hidden target layer keeps the button enabled and is refused by
/// [`straighten`] with [`STRAIGHTEN_HIDDEN_ERROR`], and the states the ticket marks *not measured*
/// (a layer with a mask, a shape, vector or adjustment layer, artboards, and the lock kinds other
/// than Lock All and Lock Position) keep today's behaviour. A document with no active layer keeps
/// turning the whole canvas as it does now; an active id the document no longer holds is refused.
fn straighten_disabled(s: &Session) -> Option<&'static str> {
let st = s.active()?;
if st.selected_layers().len() > 1 {
return Some("several layers selected");
}
// The active layer is the one the Layers panel targets; with none, the command turns the
// canvas, which the reference was not measured for.
let id = st.active_layer?;
// An id the document no longer holds: `Session::edit` keeps the *selected* layers valid but
// not the active one, so an edit that drops the active layer can leave a stale id behind.
// Turning and cropping the whole canvas for a layer that is not there is the worse answer, and
// `select_layer` and `restore_layer_selection` both refuse such an id.
let Some(layer) = st.doc.layer(id) else {
return Some("no active layer");
};
if st.doc.is_background(id) {
return Some("the Background");
}
if layer.is_group() {
return Some("a group");
}
// Locks inherited from a group count, as they do for the Move tool.
let locks = st.doc.effective_locks(id);
if locks.all {
return Some("the layer is locked");
}
if locks.position {
return Some("the layer's position is locked");
}
None
}
fn has_log(s: &Session) -> std::result::Result<(), String> {
if s.analysis.log.is_empty() { Err("the Measurement Log is empty".into()) } else { Ok(()) }
}
@@ -207,7 +266,7 @@ pub(crate) fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess
Ok(v)
}
Err(e) => {
st.doc = before;
let failed = std::mem::replace(&mut st.doc, before);
st.active_layer = prior.active;
st.selected_layers = prior.selected;
st.layer_anchor = anchor;
@@ -220,7 +279,9 @@ pub(crate) fn compound<R>(s: &mut Session, label: &str, f: impl FnOnce(&mut Sess
if was_clean {
st.saved_revision = st.revision;
}
st.last_damage = None;
// This revision's damage; `Session::dispatch` reports the command's whole span (nothing,
// when the inner commands had changed pixels and the restore took them back).
st.last_damage = crate::layer_multi_cmds::step_damage(&failed, &st.doc);
Err(e)
}
};
@@ -718,6 +779,12 @@ pub fn straighten_angle(r: &Ruler) -> f64 {
fn straighten(s: &mut Session, p: &Value) -> Result<Value> {
let d = doc(s)?;
let r = d.measurement.ruler.ok_or_else(|| EngineError::Other("no ruler line".into()))?;
// A hidden target layer keeps its button and gets this alert instead of a rotation (#12033).
// Asked before anything is read for the edit, so the document, its History and the ruler line
// stay exactly as they were; a layer inside a hidden group is hidden too (#571).
if s.active().and_then(|st| st.active_layer).is_some_and(|id| d.path_of(id).is_some_and(|path| !d.shown_at(&path))) {
return Err(EngineError::Other(STRAIGHTEN_HIDDEN_ERROR.into()));
}
let rot = straighten_angle(&r);
if rot.abs() < 1e-9 {
return Ok(json!({"angle": 0.0}));
@@ -796,7 +863,7 @@ fn count_add(s: &mut Session, p: &Value) -> Result<Value> {
if gi.is_some_and(|i| i >= group_count) {
return Err(bad("count.add", "no such group"));
}
let n = s.edit("Count", |d, _| {
let n = s.edit("Add Count Object", |d, _| {
if d.measurement.count_groups.is_empty() {
let g = new_group(d, None, None);
d.measurement.count_groups.push(g);
@@ -846,7 +913,7 @@ fn locate(s: &Session, p: &Value, cmd: &str) -> Result<(usize, usize)> {
fn count_remove(s: &mut Session, p: &Value) -> Result<Value> {
let (g, i) = locate(s, p, "count.remove")?;
s.edit("Count", |d, _| {
s.edit("Delete Count Object", |d, _| {
d.measurement.count_groups[g].points.remove(i);
Ok(())
})?;
@@ -856,7 +923,7 @@ fn count_remove(s: &mut Session, p: &Value) -> Result<Value> {
fn count_move(s: &mut Session, p: &Value) -> Result<Value> {
let to = point(p.get("to")).ok_or_else(|| bad("count.move", "pass `to`: [x, y]"))?;
let (g, i) = locate(s, p, "count.move")?;
s.edit("Count", |d, _| {
s.edit("Drag Count Object", |d, _| {
d.measurement.count_groups[g].points[i] = to;
Ok(())
})?;
@@ -881,7 +948,7 @@ fn count_clear(s: &mut Session, p: &Value) -> Result<Value> {
fn count_new_group(s: &mut Session, p: &Value) -> Result<Value> {
let name = p.get("name").and_then(Value::as_str).map(str::to_string);
let color = color_of("count.newGroup", p, "color")?;
s.edit("New Count Group", |d, _| {
s.edit("Add Count Group", |d, _| {
let g = new_group(d, name, color);
d.measurement.count_groups.push(g);
d.measurement.active_count_group = d.measurement.count_groups.len() - 1;
@@ -949,8 +1016,24 @@ fn count_set_group(s: &mut Session, p: &Value) -> Result<Value> {
}
let activate = p.get("active").and_then(Value::as_bool) == Some(true) || p.as_object().is_some_and(|o| o.len() == 1 && o.contains_key("group"));
let changed = grp != d.measurement.count_groups[g];
if changed || (activate && d.measurement.active_count_group != g) {
s.edit("Count Group Options", |d, _| {
let switches = activate && d.measurement.active_count_group != g;
if changed || switches {
// One field changed: Photoshop's name for it (#11763). Several fields, or a switch of the
// current group (not measured), keep "Count Group Options".
let old = &d.measurement.count_groups[g];
let fields = [
(grp.name != old.name, "Set Count Group Name"),
(grp.visible != old.visible, "Set Count Group Visibility"),
(grp.color != old.color, "Set Count Draw Color"),
(grp.marker_size != old.marker_size, "Set Count Marker Size"),
(grp.label_size != old.label_size, "Set Count Font Size"),
];
let mut one = fields.iter().filter(|(c, _)| *c).map(|(_, l)| *l);
let label = match (one.next(), one.next()) {
(Some(l), None) if !switches => l,
_ => "Count Group Options",
};
s.edit(label, |d, _| {
d.measurement.count_groups[g] = grp;
if activate {
d.measurement.active_count_group = g;
@@ -1018,7 +1101,9 @@ fn record(s: &mut Session, p: &Value) -> Result<Value> {
other => return Err(bad(CMD, format!("unknown source `{other}` (auto|selection|ruler|count)"))),
};
// Numbered only once the rows exist, so a failed measurement does not use up a label.
let label = format!("Measurement {}", s.analysis.next_measurement + 1);
// A count's row is "Count N" (#11775); the number is the shared one.
let word = if source == "count" { "Count" } else { "Measurement" };
let label = format!("{word} {}", s.analysis.next_measurement + 1);
let now = p.get("dateTime").and_then(Value::as_str).map(str::to_string).unwrap_or_else(now_iso);
let factor = d.measurement.scale.factor();
let mut rows: Vec<Map<String, Value>> = Vec::new();
@@ -1297,8 +1382,8 @@ pub fn specs() -> Vec<CommandSpec> {
"image.analysis.straightenLayer",
"Straighten Layer",
[],
r##"{"crop":bool=(active layer is the Background)} (rotates so the ruler line is level; crop = rotate the canvas and crop to the image)"##,
has_ruler,
r##"{"crop":bool=(active layer is the Background)} (rotates so the ruler line is level; crop = rotate the canvas and crop to the image; off for the Background, two or more selected layers, a group, Lock All and Lock Position, and a hidden target layer answers "Could not straighten the layer because the target layer is hidden." with nothing changed (#12033))"##,
has_straightenable_layer,
straighten,
true
),
@@ -1332,5 +1417,8 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
#[cfg(test)]
#[path = "analysis_straighten_enabled_tests.rs"]
mod analysis_straighten_enabled_tests;
#[cfg(test)]
mod tests;
+5 -2
View File
@@ -231,10 +231,13 @@ fn straighten_layer_and_image() {
assert_eq!(s.active().unwrap().history.past_len(), before + 1, "one history step");
assert_eq!(d(&s).size.width, 80);
assert!(d(&s).measurement.ruler.is_none());
// The Background: rotate the canvas and crop to the image.
// The Background used to rotate the canvas and crop it to the image; #12033 greys that state
// out, so the same crop now happens on a layer and only when it is asked for.
let mut s = session(80, 60, 16);
s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [40, 40]})).unwrap();
let r = s.execute("image.analysis.straightenLayer", json!({})).unwrap();
assert!(!s.is_enabled("image.analysis.straightenLayer"), "the Background is greyed out (#12033)");
s.execute("layer.new.layer", json!({})).unwrap();
let r = s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap();
assert_eq!(r["cropped"], true);
assert_eq!(r["angle"].as_f64().unwrap().abs(), 45.0);
let nd = d(&s);
@@ -0,0 +1,283 @@
//! Straighten Layer's enabled states and its hidden-layer refusal, measured against the reference
//! application (#12033).
//!
//! With a ruler line drawn the reference greys the button out for the Background, two or more
//! selected layers, a group, a layer with Lock All and a layer with Lock Position. A hidden target
//! layer keeps the button enabled: the click answers an alert ("Could not straighten the layer
//! because the target layer is hidden.") and nothing changes. Pixel, text and smart object layers
//! stay enabled and are rotated.
//!
//! A layer with a mask, a shape or vector layer, an adjustment layer, artboards and the other lock
//! kinds are *not measured* there: they keep today's behaviour, so the tests below only pin that
//! the new check does not reach them.
use photocraft_doc::LayerId;
use super::*;
const CMD: &str = "image.analysis.straightenLayer";
/// A white document with a Background, as File > New makes one.
fn session(w: u32, h: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": w, "height": h, "background": "white"})).unwrap();
s
}
/// The same document in CMYK at 16 bits, which the reference also straightens.
fn cmyk_16(w: u32, h: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": w, "height": h, "mode": "cmyk", "depth": 16, "background": "white"})).unwrap();
s
}
/// A ruler line to straighten by: without one the command is off for every target.
fn rule(s: &mut Session) {
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
}
/// A block of opaque pixels on the layer: an empty layer has nothing to transform, which would
/// hide the state under test behind "nothing to transform". The colour has the layer's own channel
/// count, so it works for RGB, Grayscale and CMYK at 8 and 16 bits alike.
fn paint(s: &mut Session, l: LayerId) {
s.edit("paint", |doc, _| {
let surf = doc.layer_mut(l).unwrap().surface_mut().unwrap();
let mut px = vec![0.0; surf.channels()];
if let Some(first) = px.first_mut() {
*first = 1.0;
}
if let Some(last) = px.last_mut() {
*last = 1.0;
}
surf.fill_rect(Rect::new(10, 10, 50, 20), &px);
Ok(())
})
.unwrap();
}
/// A new pixel layer with something on it, which `layer.new.layer` makes the active one.
fn pixel_layer(s: &mut Session, name: &str) -> LayerId {
let l = LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap());
paint(s, l);
l
}
/// A type layer over the canvas.
fn text_layer(s: &mut Session) -> LayerId {
LayerId(s.execute("type.create", json!({"x": 40, "y": 50, "text": "Hi", "size": 20})).unwrap()["layer"].as_u64().unwrap())
}
/// A pixel layer turned into a smart object.
fn smart_layer(s: &mut Session) -> LayerId {
let l = pixel_layer(s, "Smart");
s.execute("layer.smartObjects.convertToSmartObject", json!({"layer": l.0})).unwrap();
l
}
fn doc_of(s: &Session) -> Arc<Document> {
s.active().unwrap().doc.clone()
}
fn steps(s: &Session) -> usize {
s.active().unwrap().history.past_len()
}
/// A state the reference greys the button out for: the engine says the command is off, so the menu
/// item and the options-bar button follow, and a call answered anyway (the CLI, the control channel,
/// an action step) is refused as a disabled command rather than run. Nothing is touched: the
/// document is the same `Arc`, no History step is added and the ruler line stays.
fn assert_greyed(s: &mut Session, what: &str) {
let (before, history) = (doc_of(s), steps(s));
assert!(!s.is_enabled(CMD), "{what}: the button is greyed out");
let e = s.execute(CMD, json!({})).unwrap_err();
let disabled = matches!(&e, EngineError::Disabled(id, _) if id == CMD);
assert!(disabled, "{what}: refused as a disabled command, got {e}");
assert!(Arc::ptr_eq(&before, &doc_of(s)), "{what}: the document was not touched");
assert_eq!(steps(s), history, "{what}: no History step");
assert!(doc_of(s).measurement.ruler.is_some(), "{what}: the ruler line is still there");
}
/// The angle the ruler line of [`rule`] straightens by.
const ROT: f64 = 4.7636;
#[test]
fn the_background_greys_straighten_layer_out() {
// Today it rotates the canvas and crops it (800 x 600 becomes 500 x 375); the reference has no
// button for it at all.
let mut s = session(100, 80);
assert!(doc_of(&s).is_background(s.active().unwrap().active_layer.unwrap()), "the Background is the target");
rule(&mut s);
assert_greyed(&mut s, "the Background");
}
#[test]
fn two_selected_layers_grey_straighten_layer_out() {
let mut s = session(100, 80);
let a = pixel_layer(&mut s, "One");
let b = pixel_layer(&mut s, "Two");
s.execute("layer.select", json!({"layer": a.0})).unwrap();
s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap();
assert_eq!(s.active().unwrap().selected_layers().len(), 2, "both selected");
rule(&mut s);
assert_greyed(&mut s, "two selected layers");
// Back to one layer, the button is live again.
s.execute("layer.select", json!({"layer": b.0})).unwrap();
assert!(s.is_enabled(CMD), "one selected layer");
}
#[test]
fn a_group_greys_straighten_layer_out() {
let mut s = session(100, 80);
pixel_layer(&mut s, "Inner");
s.execute("layer.groupLayers", json!({})).unwrap();
let g = s.active().unwrap().active_layer.unwrap();
assert!(doc_of(&s).layer(g).unwrap().is_group(), "the new group is the target");
rule(&mut s);
assert_greyed(&mut s, "a group");
// A layer inside the group is a layer, so the button is on for it.
let inner = doc_of(&s).layer(g).unwrap().children().unwrap()[0].id;
s.execute("layer.select", json!({"layer": inner.0})).unwrap();
assert!(s.is_enabled(CMD), "a layer in a group");
}
#[test]
fn lock_all_and_lock_position_grey_straighten_layer_out() {
// Measured: both grey the button. Today it is enabled and the command fails with
// `layer "Colors" is locked`, which is what a greyed button cannot do any more.
for key in ["all", "position"] {
let mut s = session(100, 80);
let l = pixel_layer(&mut s, "Colors");
s.execute("layer.setProps", json!({"layer": l.0, "locks": {key: true}})).unwrap();
rule(&mut s);
assert_greyed(&mut s, &format!("Lock {}", if key == "all" { "All" } else { "Position" }));
}
}
#[test]
fn the_other_lock_kinds_are_not_reached_by_the_new_check() {
// Not measured in the reference, so they keep today's behaviour: the button stays on and the
// command answers as it does now.
for key in ["transparency", "pixels", "artboard"] {
let mut s = session(100, 80);
let l = pixel_layer(&mut s, "Colors");
s.execute("layer.setProps", json!({"layer": l.0, "locks": {key: true}})).unwrap();
rule(&mut s);
assert!(s.is_enabled(CMD), "Lock {key}: not measured, still enabled");
}
}
#[test]
fn a_hidden_layer_stays_enabled_and_is_refused_with_the_alert() {
// The one measured refusal: the button is on, the click shows the alert and nothing changes.
let mut s = session(100, 80);
let l = pixel_layer(&mut s, "Gone");
s.execute("layer.setProps", json!({"layer": l.0, "visible": false})).unwrap();
rule(&mut s);
let (before, history) = (doc_of(&s), steps(&s));
assert!(s.is_enabled(CMD), "a hidden layer keeps the button on");
let e = s.execute(CMD, json!({})).unwrap_err();
assert_eq!(e.to_string(), STRAIGHTEN_HIDDEN_ERROR, "the reference's alert text");
assert!(matches!(e, EngineError::Other(_)), "an alert, not a greyed state: {e}");
assert!(Arc::ptr_eq(&before, &doc_of(&s)), "nothing changed");
assert_eq!(steps(&s), history, "no History step");
assert!(doc_of(&s).measurement.ruler.is_some(), "a straighten that never ran leaves the ruler line");
}
#[test]
fn a_layer_hidden_with_its_group_is_refused_the_same_way() {
// A layer inside a hidden group is hidden, as for the painting tools (#571).
let mut s = session(100, 80);
let l = pixel_layer(&mut s, "Inner");
s.execute("layer.groupLayers", json!({})).unwrap();
let g = s.active().unwrap().active_layer.unwrap();
s.execute("layer.setProps", json!({"layer": g.0, "visible": false})).unwrap();
s.execute("layer.select", json!({"layer": l.0})).unwrap();
rule(&mut s);
let (before, history) = (doc_of(&s), steps(&s));
assert!(s.is_enabled(CMD), "the target is a layer, not the group");
assert_eq!(s.execute(CMD, json!({})).unwrap_err().to_string(), STRAIGHTEN_HIDDEN_ERROR);
assert!(Arc::ptr_eq(&before, &doc_of(&s)));
assert_eq!(steps(&s), history);
}
#[test]
fn without_a_ruler_line_the_button_stays_greyed_for_every_layer() {
let mut s = session(100, 80);
pixel_layer(&mut s, "Paint");
assert!(!s.is_enabled(CMD), "no ruler line");
s.execute("layer.setProps", json!({"layer": s.active().unwrap().active_layer.unwrap().0, "visible": false})).unwrap();
assert!(!s.is_enabled(CMD), "a hidden layer without a ruler line stays greyed, not enabled");
}
#[test]
fn an_active_layer_the_document_no_longer_holds_is_refused() {
// `Session::edit` prunes the selected layers but not the active id, so an edit that drops the
// active layer can leave one behind (`select_layer` and `restore_layer_selection` both refuse
// such an id). The command must then say it is off, not rotate and crop the whole canvas for a
// layer that is not there.
let mut s = session(100, 80);
let l = pixel_layer(&mut s, "Gone");
s.edit("drop", |doc, _| {
doc.layers.retain(|layer| layer.id != l);
Ok(())
})
.unwrap();
assert_eq!(s.active().unwrap().active_layer, Some(l), "the target still points at the dropped layer");
assert!(doc_of(&s).layer(l).is_none(), "and the document does not hold it");
rule(&mut s);
assert_greyed(&mut s, "an active layer that is gone");
// The destructive case this closes: `crop` asks for the canvas, which would turn and shrink for
// a target that no longer exists.
let size = (doc_of(&s).size.width, doc_of(&s).size.height);
assert!(s.execute(CMD, json!({"crop": true})).is_err());
assert_eq!((doc_of(&s).size.width, doc_of(&s).size.height), size, "the canvas kept its size");
}
#[test]
fn a_single_visible_layer_still_rotates_without_cropping() {
// The pin for the state that stays: the layer turns about the canvas centre, the canvas does not.
let mut s = session(100, 80);
pixel_layer(&mut s, "Paint");
rule(&mut s);
let (history, size) = (steps(&s), (doc_of(&s).size.width, doc_of(&s).size.height));
assert!(s.is_enabled(CMD), "a layer is what the button is for");
let r = s.execute(CMD, json!({})).unwrap();
assert_eq!(r["cropped"], false, "{r}");
assert!((r["angle"].as_f64().unwrap() - ROT).abs() < 1e-3, "{r}");
assert_eq!((doc_of(&s).size.width, doc_of(&s).size.height), size, "the canvas keeps its size");
assert_eq!(steps(&s), history + 1, "one History step");
assert!(doc_of(&s).measurement.ruler.is_none(), "the ruler line is cleared");
assert!(s.undo());
assert_eq!((doc_of(&s).size.width, doc_of(&s).size.height), size, "and one Undo takes it back");
}
#[test]
fn pixel_text_and_smart_object_layers_stay_enabled_and_rotate() {
// Measured, also in a CMYK 16-bit document.
type Maker = (&'static str, fn(&mut Session) -> LayerId);
let make: [Maker; 3] = [("pixel", |s| pixel_layer(s, "Paint")), ("type", text_layer), ("smart object", smart_layer)];
for (what, make_layer) in make {
for new in [session as fn(u32, u32) -> Session, cmyk_16] {
let mut s = new(100, 80);
make_layer(&mut s);
rule(&mut s);
assert!(s.is_enabled(CMD), "{what}: enabled");
let r = s.execute(CMD, json!({}));
let r = r.unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(r["cropped"], false, "{what}: rotated, not cropped");
assert!((r["angle"].as_f64().unwrap() - ROT).abs() < 1e-3, "{what}: {r}");
}
}
}
#[test]
fn an_explicit_crop_still_crops_for_automation() {
// The `crop` param stays available to automation where the command is enabled.
let mut s = session(100, 80);
pixel_layer(&mut s, "Paint");
rule(&mut s);
let r = s.execute(CMD, json!({"crop": true})).unwrap();
assert_eq!(r["cropped"], true, "{r}");
let d = doc_of(&s);
assert!(d.size.width < 100 && d.size.height < 80, "the canvas is rotated and cropped to {:?}", [d.size.width, d.size.height]);
}
+43 -21
View File
@@ -152,9 +152,11 @@ fn xywh(r: Rect) -> [i64; 4] {
/// it puts it right of the board, a [`GAP`] away, sliding further right past any board in the
/// way. Moves the copy, layer `id` (just inserted on top of its original), there with its
/// contents and grows the canvas to show it; anything that isn't an artboard is left alone.
pub(crate) fn place_copy(doc: &mut Document, id: LayerId) -> Result<()> {
/// Returns [`fit_canvas`]'s shift (a board already past the origin, as a PSD can hold, re-bases the
/// document), for [`follow_shift`].
pub(crate) fn place_copy(doc: &mut Document, id: LayerId) -> Result<(i32, i32)> {
let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
let Some(r) = l.artboard().map(|a| a.rect) else { return Ok(()) };
let Some(r) = l.artboard().map(|a| a.rect) else { return Ok((0, 0)) };
let name = l.name.clone();
let boards: Vec<Rect> = doc.artboards().iter().filter(|b| b.0 != id).map(|b| b.2.rect).collect();
let (y0, y1, w) = (i64::from(r.y0), i64::from(r.y1), i64::from(r.width()));
@@ -180,8 +182,7 @@ pub(crate) fn place_copy(doc: &mut Document, id: LayerId) -> Result<()> {
let copy = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
crate::commands::translate_layer(&snapshot, copy, dx, 0);
crate::vector_cmds::translate_vectors(&snapshot, copy, f64::from(dx), 0.0);
fit_canvas(doc);
Ok(())
Ok(fit_canvas(doc))
}
/// Record a Duplicate's `inPlace` only when a copy (the selection after it) is an artboard: for
@@ -203,8 +204,11 @@ pub(crate) fn recorded_duplicate(s: &Session, mut p: Value) -> Value {
/// contents, guides, paths…) right/down by its overhang, then the canvas grows to show it. An
/// axis whose boards span more than the largest canvas, or a shift that would push pixels past
/// the 32-bit range, stays unshifted: the board stays partly off-canvas, as one past the size
/// limit does.
pub(crate) fn fit_canvas(doc: &mut Document) {
/// limit does. Returns the shift, for [`follow_shift`]: `translate_doc` moves the document's own
/// geometry, but the session's Color Sampler points and painting symmetry stay behind unless the
/// caller passes it on.
#[must_use = "pass the shift to `follow_shift`, or the Color Samplers and symmetry stay behind (#9302)"]
pub(crate) fn fit_canvas(doc: &mut Document) -> (i32, i32) {
let max = i64::from(crate::document_preset_cmds::MAX_DIMENSION);
let boards: Vec<Rect> = doc.artboards().iter().map(|b| b.2.rect).collect();
// The canvas and every board, per axis (`lo` ≤ 0 is the canvas origin or a board past it).
@@ -226,6 +230,20 @@ pub(crate) fn fit_canvas(doc: &mut Document) {
// shapes against it, leaving them missing or clipped (#2389).
crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes);
}
(sx, sy)
}
/// Keep the Color Sampler points and the painting symmetry on their pixels after an edit shifted
/// the document by `(dx, dy)` to show a board past the origin ([`fit_canvas`]), as Canvas Size's
/// sampler map does (#9302). View state: no history step. The canvas only grew, so every point
/// stays on it.
pub(crate) fn follow_shift(s: &mut Session, (dx, dy): (i32, i32)) {
let Some(st) = s.active_mut().filter(|_| (dx, dy) != (0, 0)) else { return };
for p in &mut st.color_samplers {
*p = [p[0] + f64::from(dx), p[1] + f64::from(dy)];
}
let a = photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy));
st.symmetry = st.symmetry.take().and_then(|sym| sym.transform(&a));
}
fn next_artboard_name(doc: &Document) -> String {
@@ -294,7 +312,7 @@ fn new_artboard(s: &mut Session, p: &Value) -> Result<Value> {
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "`takeBackground` must be true or false"))?,
};
let id = s.edit("New Artboard", |doc, active| {
let (id, shift) = s.edit("New Artboard", |doc, active| {
let mut g = Layer::group(name.unwrap_or_else(|| next_artboard_name(doc)), vec![]);
set_artboard(&mut g, Artboard { rect, background, preset });
// Only the first board takes the Background in (decided before the board exists).
@@ -303,10 +321,11 @@ fn new_artboard(s: &mut Session, p: &Value) -> Result<Value> {
if take {
move_background_into(doc, id);
}
fit_canvas(doc);
let shift = fit_canvas(doc);
*active = Some(id);
Ok(id)
Ok((id, shift))
})?;
follow_shift(s, shift);
crate::layer_multi_cmds::set_selection(s, vec![id], Some(id), Some(id))?;
Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
}
@@ -344,17 +363,18 @@ fn artboard_from_group(s: &mut Session, p: &Value) -> Result<Value> {
}
let canvas = d.doc.bounds();
let background = if apply_background { background_param(p, cmd)?.unwrap_or_default() } else { ArtboardBackground::White };
let rect = s.edit("Artboard from Group", |doc, active| {
let (rect, shift) = s.edit("Artboard from Group", |doc, active| {
if !doc.layers.iter().any(|t| t.id == id && t.is_group() && t.artboard().is_none()) {
return Err(EngineError::Other("artboards are made from a top-level layer group".into()));
}
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
let rect = crate::layer_multi_cmds::layer_bounds(l).unwrap_or(canvas);
set_artboard(l, Artboard { rect, background, preset });
fit_canvas(doc);
let shift = fit_canvas(doc);
*active = Some(id);
Ok(rect)
Ok((rect, shift))
})?;
follow_shift(s, shift);
crate::layer_multi_cmds::set_selection(s, vec![id], Some(id), Some(id))?;
Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
}
@@ -388,7 +408,7 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
// A size of the user's own (a post, a story…) from the layers' top left; 0 or none keeps
// their bounds on that axis (#9087).
let size = [int(p, "width").filter(|v| *v != 0), int(p, "height").filter(|v| *v != 0)];
let (gid, rect) = s.edit("Artboard from Layers", |doc, active| {
let (gid, rect, shift) = s.edit("Artboard from Layers", |doc, active| {
let ids = crate::layer_multi_cmds::top_level(doc, &sel);
if ids.is_empty() || ids.iter().any(|id| doc.artboard_of(*id).is_some()) {
return Err(EngineError::Other("select layers that are not in an artboard".into()));
@@ -403,10 +423,11 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
set_artboard(&mut g, Artboard { rect, background, preset: String::new() });
let gid = doc.insert_above(None, g);
crate::layer_multi_cmds::check_group_depth(doc, "Artboard from Layers")?;
fit_canvas(doc);
let shift = fit_canvas(doc);
*active = Some(gid);
Ok((gid, rect))
Ok((gid, rect, shift))
})?;
follow_shift(s, shift);
crate::layer_multi_cmds::set_selection(s, vec![gid], Some(gid), Some(gid))?;
Ok(json!({"layer": gid.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
}
@@ -445,7 +466,7 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
));
}
};
s.edit("Edit Artboard", |doc, _| {
let shift = s.edit("Edit Artboard", |doc, _| {
if move_contents && (dx, dy) != (0, 0) {
let snapshot = doc.clone();
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
@@ -467,9 +488,9 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
None if rect.width() != old.rect.width() || rect.height() != old.rect.height() => a.preset.clear(),
None => {}
}
fit_canvas(doc);
Ok(())
Ok(fit_canvas(doc))
})?;
follow_shift(s, shift);
Ok(json!({"layer": id.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
}
@@ -546,7 +567,7 @@ fn add_beside(s: &mut Session, p: &Value) -> Result<Value> {
let grown = |len: u32, by: i32| (i64::from(len) + i64::from(by)).clamp(1, 300_000) as u32;
let label = if duplicate { "Duplicate Artboard" } else { "New Artboard" };
let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true);
let (nid, rect) = s.edit(label, |doc, active| {
let (nid, rect, (fx, fy)) = s.edit(label, |doc, active| {
if (sx, sy) != (0, 0) {
crate::image_cmds::translate_doc(doc, cmd, sx, sy)?;
doc.size = Size::new(grown(doc.size.width, sx), grown(doc.size.height, sy));
@@ -575,10 +596,11 @@ fn add_beside(s: &mut Session, p: &Value) -> Result<Value> {
set_artboard(&mut g, Artboard { rect, background: src.background, preset: src.preset.clone() });
doc.insert_above(Some(id), g)
};
fit_canvas(doc);
let fitted = fit_canvas(doc);
*active = Some(nid);
Ok((nid, rect))
Ok((nid, rect, fitted))
})?;
follow_shift(s, (sx.saturating_add(fx), sy.saturating_add(fy)));
crate::layer_multi_cmds::set_selection(s, vec![nid], Some(nid), Some(nid))?;
Ok(json!({"layer": nid.0, "rect": [rect.x0, rect.y0, rect.width(), rect.height()]}))
}
@@ -723,6 +723,87 @@ fn moving_an_artboard_left_of_or_above_the_origin_grows_the_canvas_there() {
}
}
#[test]
fn a_board_past_the_origin_moves_the_color_samplers_and_symmetry_with_the_document() {
// #9302: the re-based document moved everything but the Color Sampler points and the
// painting symmetry, which then sat on other pixels. They follow, as with Canvas Size.
let samplers = |s: &Session| s.active().unwrap().color_samplers.clone();
let center = |s: &Session| s.active().unwrap().symmetry.as_ref().and_then(|y| y.preset()).map(|p| p.center);
for (cmd, p) in [("layer.translate", json!({"dx": -60, "dy": -30})), ("layer.artboard.set", json!({"x": -50, "y": -20}))] {
let mut s = session(8);
let gid = board_with_square(&mut s);
s.execute("view.colorSamplers.add", json!({"x": 15, "y": 15})).unwrap();
s.execute("paint.setSymmetry", json!({"mode": "vertical", "center": [70.0, 20.0]})).unwrap();
s.execute("layer.select", json!({"layer": gid.0})).unwrap();
s.execute(cmd, p).unwrap();
// The board lands at (0, 0) after the document shifted right 50 and down 20; the sampler
// is pinned to the canvas, not the board, so it shifts with the document only.
assert_eq!(board_rect(&s, gid.0), Rect::new(0, 0, 40, 40), "{cmd}");
assert_eq!(samplers(&s), vec![[65.0, 35.0]], "{cmd}");
assert_eq!(center(&s), Some([120.0, 40.0]), "{cmd}: the symmetry stays on its pixels");
}
// A new board left of the canvas shifts the photo right by its overhang.
let mut s = session(8);
add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]);
s.execute("view.colorSamplers.add", json!({"x": 15, "y": 15})).unwrap();
s.execute("layer.new.artboard", json!({"rect": [-200, 0, 100, 80]})).unwrap();
assert_eq!(samplers(&s), vec![[215.0, 15.0]]);
assert!(red_at(&s, 215, 15));
// A board made from layers (or a group) left of the canvas shifts by their overhang.
for cmd in ["layer.new.artboardFromLayers", "layer.new.artboardFromGroup"] {
let mut s = session(8);
add_square(&mut s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]);
s.execute("view.colorSamplers.add", json!({"x": 15, "y": 15})).unwrap();
add_square(&mut s, Rect::new(-30, 40, -10, 60), [0.0, 0.0, 1.0, 1.0]);
if cmd.ends_with("Group") {
s.execute("layer.groupLayers", json!({})).unwrap();
}
s.execute(cmd, json!({})).unwrap();
assert_eq!(samplers(&s), vec![[45.0, 15.0]], "{cmd}");
assert!(red_at(&s, 45, 15), "{cmd}");
}
// The "+" button left of a board at the origin shifts by the board and the gap.
let mut s = session(8);
let gid = board_with_square(&mut s);
s.execute("layer.artboard.set", json!({"x": 0, "y": 0})).unwrap();
s.execute("view.colorSamplers.add", json!({"x": 5, "y": 5})).unwrap();
s.execute("layer.artboard.addBeside", json!({"layer": gid.0, "side": "left"})).unwrap();
let by = 40 + GAP;
assert_eq!(board_rect(&s, gid.0), Rect::new(by, 0, by + 40, 40));
assert_eq!(samplers(&s), vec![[f64::from(by) + 5.0, 5.0]]);
assert!(red_at(&s, by + 5, 5));
// A board right of the canvas shifts nothing.
s.execute("layer.artboard.addBeside", json!({"layer": gid.0, "side": "right"})).unwrap();
assert_eq!(samplers(&s), vec![[f64::from(by) + 5.0, 5.0]]);
}
#[test]
fn duplicating_a_board_beside_one_past_the_origin_moves_the_color_samplers_with_the_document() {
// #9302 review: Layer › Duplicate puts the copy right of its board, but `fit_canvas` still
// re-bases a document whose boards were already past the origin (as a PSD can hold them).
// Single (`layer`) and several selected layers (`duplicate_selected`) both follow the shift.
for multi in [false, true] {
let mut s = session(8);
let gid = board_with_square(&mut s);
s.edit("past the origin", |doc, _| {
doc.layer_mut(gid).and_then(|l| l.artboard_mut()).unwrap().rect = Rect::new(-40, 10, 0, 50);
Ok(())
})
.unwrap();
let sq = add_square(&mut s, Rect::new(60, 10, 80, 30), [1.0, 0.0, 0.0, 1.0]);
s.execute("view.colorSamplers.add", json!({"x": 65, "y": 15})).unwrap();
if multi {
crate::layer_multi_cmds::set_selection(&mut s, vec![gid, sq], Some(gid), Some(gid)).unwrap();
s.execute("layer.duplicate", json!({})).unwrap();
} else {
s.execute("layer.duplicate", json!({"layer": gid.0})).unwrap();
}
assert_eq!(board_rect(&s, gid.0), Rect::new(0, 10, 40, 50), "multi {multi}: the document shifted right 40");
assert_eq!(s.active().unwrap().color_samplers, vec![[105.0, 15.0]], "multi {multi}");
assert!(red_at(&s, 105, 15), "multi {multi}: the sampler is still on the square");
}
}
#[test]
fn add_beside_places_a_board_on_each_side_and_alt_duplicates_contents() {
// #3033: the Artboard tool's "+" buttons. Board 40×40 at (10, 10) holding a red square.
+4
View File
@@ -50,6 +50,7 @@ mod steps_layer;
mod steps_layer_style;
mod steps_lookup;
mod steps_make;
mod steps_measurement;
mod steps_path;
mod steps_perspective_warp;
mod steps_type_path;
@@ -187,6 +188,9 @@ mod layer_props_tests;
#[cfg(test)]
mod stylize_tests;
#[cfg(test)]
mod measurement_tests;
#[cfg(test)]
mod selection_tests;
+4
View File
@@ -616,6 +616,9 @@ pub(super) const EVENTS: &[Event] = &[
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.
// The label is interchange data, not a display name: Save Actions writes it into the step's
// dictionary (convert.rs), so it stays Photoshop's wording and a loaded step round-trips. The
// menu item and window title come from `lens_cmds` and read "RAW Develop Filter".
Event { code: "", name: "Adobe Camera Raw Filter", label: "Camera Raw Filter", ids: &[crate::lens_cmds::RAW], from: camera_raw_from, to: camera_raw_to },
// Video, Other, Average and matting (#10607).
Event {
@@ -893,6 +896,7 @@ pub(super) const EVENTS: &[Event] = &[
name: "set",
label: "Set",
ids: &[
super::steps_measurement::SET_SCALE,
"select.all",
"select.deselect",
"select.reselect",
@@ -0,0 +1,174 @@
//! #10723: Image › Analysis › Set Measurement Scale › Custom steps, recorded as a Set of the
//! document's `measurementScale` property (`docs/atn.md`, "Recorded through the menus").
use super::*;
const SET_SCALE: &str = "image.analysis.setMeasurementScale";
const SOURCE: &str = "_atnMeasurementScaleDescriptor";
/// The `T ` object of the measured step, built here independently of the converter.
fn scale(class: &str, pixels: i32, logical: f64, units: &str) -> Descriptor {
Descriptor::new(class)
.with("pixelLength", D::Integer(pixels))
.with("logicalLength", D::Double(logical))
.with("logicalUnits", D::Text(UnicodeString::new_nul(units)))
}
/// The measured Set: `null` is the `measurementScale` property of the target document.
fn recorded(t: Descriptor) -> Descriptor {
let target = D::Reference(vec![
ReferenceItem::Property { class: class("Prpr"), key: Id::new("measurementScale") },
ReferenceItem::Enumerated { class: class("Dcmn"), type_id: Id::new("Ordn"), value: Id::new("Trgt") },
]);
Descriptor::new("null").with("null", target).with("T ", D::Descriptor(t))
}
fn set_item(d: Descriptor) -> AtnItem {
AtnItem { event: AtnEvent::Code(*b"setd"), dictionary: b"Set".to_vec(), descriptor: Some(d), ..Default::default() }
}
/// Load `items` as action "A" through `actions.load`.
fn load(items: Vec<AtnItem>) -> (Session, Value) {
let file = AtnFile {
name: UnicodeString::new_nul("Analysis"),
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }],
..Default::default()
};
let mut s = Session::new();
let r = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&atn::write(&file).unwrap())})).unwrap();
(s, r)
}
/// Action "A" written by `actions.save` and parsed back.
fn saved(s: &mut Session) -> Vec<AtnItem> {
let r = s.execute("actions.save", json!({"action": "A"})).unwrap();
assert_eq!(r["skipped"], json!([]), "{r}");
atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap().actions.remove(0).items
}
/// The recorded step loads as a custom scale and saves back byte for byte, whatever class its
/// `T ` object was recorded with and in whatever key order.
#[test]
fn a_recorded_scale_step_loads_and_saves_back_unchanged() {
let mut reordered = scale("measurementScale", 50, 2.5, "cm");
reordered.items.reverse();
for (t, pixels, logical, units) in
[(scale("measurementScale", 120, 3.0, "mm"), 120, 3.0, "mm"), (scale("null", 100, 25.4, "inches"), 100, 25.4, "inches"), (reordered, 50, 2.5, "cm")]
{
let d = recorded(t);
let (mut s, r) = load(vec![set_item(d.clone())]);
assert_eq!(r["unsupported"], json!([]), "{r}");
let (id, p) = &s.actions.list[0].steps[0];
assert_eq!(id, SET_SCALE);
assert_eq!(
(&p["preset"], p["pixelLength"].as_f64(), p["logicalLength"].as_f64(), &p["units"]),
(&json!("custom"), Some(f64::from(pixels)), Some(logical), &json!(units)),
"{p}"
);
let back = saved(&mut s);
assert_eq!((&back[0].event, back[0].descriptor.as_ref().map(Descriptor::to_bytes)), (&AtnEvent::Code(*b"setd"), Some(d.to_bytes())));
}
}
/// A loaded step sets the document's scale, as one undoable edit.
#[test]
fn a_loaded_scale_step_plays_and_undoes() {
let (mut s, _) = load(vec![set_item(recorded(scale("measurementScale", 120, 3.0, "mm")))]);
s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
assert_eq!(played["ran"], 1, "{played}");
let read = s.execute(SET_SCALE, json!({})).unwrap();
assert_eq!(
(&read["pixelLength"], &read["logicalLength"], &read["units"], &read["default"]),
(&json!(120.0), &json!(3.0), &json!("mm"), &json!(false)),
"{read}"
);
s.execute("history.undo", json!({})).unwrap();
assert_eq!(s.execute(SET_SCALE, json!({})).unwrap()["default"], json!(true));
}
/// The step PhotoCraft writes for a native custom scale is the measured form, with `T ` of
/// class `measurementScale`, and it loads back without a stored descriptor.
#[test]
fn a_native_scale_saves_the_measured_form() {
let p = json!({"preset": "custom", "pixelLength": 120, "logicalLength": 3, "units": "mm"});
let d = export_item(SET_SCALE, &p, "S").and_then(|item| item.descriptor).unwrap();
assert_eq!(d, recorded(scale("measurementScale", 120, 3.0, "mm")));
let (s, _) = load(vec![set_item(d)]);
assert_eq!(s.actions.list[0].steps[0].1, p);
// `logicalUnits` is the command's other spelling of `units`, and the preset defaults to custom.
let other = json!({"pixelLength": 120, "logicalLength": 3, "logicalUnits": "mm"});
assert_eq!(export_item(SET_SCALE, &other, "S").and_then(|item| item.descriptor), Some(recorded(scale("measurementScale", 120, 3.0, "mm"))));
}
/// A native step the event can't hold is refused: reading the scale, the default preset, a
/// value left to the current scale, a fractional pixel length (the event stores a long), blank
/// units, or another key.
#[test]
fn settings_the_event_cannot_hold_are_refused() {
for p in [
json!({}),
json!({"preset": "default"}),
json!({"preset": "query"}),
json!({"preset": "custom", "pixelLength": 120, "logicalLength": 3}),
json!({"preset": "custom", "logicalLength": 3, "units": "mm"}),
json!({"preset": "custom", "pixelLength": 120.5, "logicalLength": 3, "units": "mm"}),
json!({"preset": "custom", "pixelLength": 0, "logicalLength": 3, "units": "mm"}),
json!({"preset": "custom", "pixelLength": 120, "logicalLength": -1, "units": "mm"}),
json!({"preset": "custom", "pixelLength": 120, "logicalLength": 3, "units": " "}),
json!({"preset": "custom", "pixelLength": 120, "logicalLength": 3, "units": "mm", "layer": 2}),
] {
assert!(export_item(SET_SCALE, &p, "S").is_none(), "{p}");
}
}
/// Any other form keeps the reference step: another target, a missing or extra key, values of
/// another type, or values the native command refuses.
#[test]
fn other_forms_keep_the_photoshop_step() {
let with = |key: &str, v: D| {
let mut t = scale("measurementScale", 120, 3.0, "mm");
if let Some(slot) = t.items.iter_mut().find(|(k, _)| k.is(key)) {
slot.1 = v;
}
recorded(t)
};
let mut missing = scale("measurementScale", 120, 3.0, "mm");
missing.items.pop();
let mut layer_target = recorded(scale("measurementScale", 120, 3.0, "mm"));
layer_target.items[0].1 = D::Reference(vec![
ReferenceItem::Property { class: class("Prpr"), key: Id::new("measurementScale") },
ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Trgt") },
]);
let forms = [
recorded(missing),
recorded(scale("measurementScale", 120, 3.0, "mm").with("Scl ", D::Double(1.0))),
recorded(scale("measurementScale", 120, 3.0, "mm")).with("Rslt", D::Double(72.0)),
layer_target,
with("pixelLength", D::Double(120.0)),
with("logicalLength", D::Integer(3)),
with("logicalLength", D::Double(0.0)),
with("pixelLength", D::Integer(-4)),
with("logicalUnits", D::Text(UnicodeString::new_nul(" "))),
with("logicalUnits", D::Integer(1)),
];
for d in forms {
let (mut s, r) = load(vec![set_item(d.clone())]);
assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}");
assert_eq!(s.actions.list[0].steps[0].0, PHOTOSHOP_STEP, "{d:?}");
assert_eq!(saved(&mut s)[0].descriptor.as_ref().map(Descriptor::to_bytes), Some(d.to_bytes()));
}
}
/// A loaded step whose scale was changed saves the new scale, not the stale recording; one whose
/// recording is damaged still saves its settings.
#[test]
fn changed_or_damaged_steps_save_their_settings() {
let (s, _) = load(vec![set_item(recorded(scale("null", 100, 25.4, "inches")))]);
let mut p = s.actions.list[0].steps[0].1.clone();
assert!(p.get(SOURCE).is_some(), "{p}");
p["units"] = json!("cm");
assert_eq!(export_item(SET_SCALE, &p, "S").and_then(|item| item.descriptor), Some(recorded(scale("measurementScale", 100, 25.4, "cm"))));
p[SOURCE] = json!("not base64!");
assert_eq!(export_item(SET_SCALE, &p, "S").and_then(|item| item.descriptor), Some(recorded(scale("measurementScale", 100, 25.4, "cm"))));
}
@@ -1168,6 +1168,8 @@ pub(super) fn set_from(d: &Descriptor) -> Mapped {
(Some("Chnl"), Target::Property(p)) if p == "fsel" => selection_from(d),
// Quick Mask mode on (`set` of the document's quick-mask property); `clearEvent` turns it off.
(Some("Prpr"), Target::Property(p)) if p == "QucM" => step("select.editInQuickMaskMode", json!({"on": true})),
// Image › Analysis › Set Measurement Scale › Custom (#10723).
(Some("Prpr"), Target::Property(p)) if p == "measurementScale" => super::steps_measurement::from(d),
// Layer › New › Layer From Background (Photoshop records the New Layer dialog's values
// as a `set` of the Background); values other than the defaults then apply to the layer.
(Some("Lyr"), Target::Property(p)) if p == "Bckg" => background_from(d),
@@ -1272,6 +1274,7 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option<Descriptor> {
let sel = |t: D| desc("null").with("null", fsel.clone()).with("T ", t);
Some(match id {
"path.set" => return super::steps_path::to(p),
super::steps_measurement::SET_SCALE => return super::steps_measurement::to(p),
"select.all" => sel(enm("Ordn", "Al ")),
"select.deselect" => sel(enm("Ordn", "None")),
"select.reselect" => sel(enm("Ordn", "Prvs")),
@@ -0,0 +1,100 @@
//! Image › Analysis › Set Measurement Scale › Custom, recorded as a Set of the document's
//! `measurementScale` property, as `docs/atn.md` ("Recorded through the menus") measures it:
//! `T ` holds `pixelLength` (long), `logicalLength` (double) and `logicalUnits` (text) (#10723).
use super::descriptors::{class, desc, jstr, text};
use super::fields::{Mapped, step};
use super::{D, Descriptor, Id, ReferenceItem, Value, json};
/// The native command the step plays as.
pub(super) const SET_SCALE: &str = "image.analysis.setMeasurementScale";
/// The recorded descriptor, kept when it differs from the one [`to`] would write (the class
/// of `T `, key order or ID encodings), so a load and save keeps the step unchanged.
const SOURCE: &str = "_atnMeasurementScaleDescriptor";
/// The custom scale the step sets.
#[derive(Debug, PartialEq)]
struct Scale {
pixels: i32,
logical: f64,
units: String,
}
/// `null`: the `measurementScale` property of the target document.
fn target() -> D {
D::Reference(vec![
ReferenceItem::Property { class: class("Prpr"), key: Id::new("measurementScale") },
ReferenceItem::Enumerated { class: class("Dcmn"), type_id: Id::new("Ordn"), value: Id::new("Trgt") },
])
}
/// Whether `d` has each of `keys` exactly once and nothing else.
fn exactly(d: &Descriptor, keys: &[&str]) -> bool {
d.items.len() == keys.len() && keys.iter().all(|key| d.items.iter().filter(|(k, _)| k.is(key)).count() == 1)
}
/// The measured form only. A length the native command refuses (not above 0, not finite) or
/// blank units keep the step as recorded, so playback can't fail on a step that loaded.
fn recorded(d: &Descriptor) -> Option<Scale> {
if !exactly(d, &["null", "T "]) || d.get("null")? != &target() {
return None;
}
let D::Descriptor(t) = d.get("T ")? else { return None };
if !exactly(t, &["pixelLength", "logicalLength", "logicalUnits"]) {
return None;
}
let (D::Integer(pixels), D::Double(logical), D::Text(units)) = (t.get("pixelLength")?, t.get("logicalLength")?, t.get("logicalUnits")?) else {
return None;
};
let units = String::from_utf16(units.0.strip_suffix(&[0]).unwrap_or(&units.0)).ok()?;
(*pixels > 0 && logical.is_finite() && *logical > 0.0 && !units.trim().is_empty()).then_some(Scale { pixels: *pixels, logical: *logical, units })
}
/// The descriptor a step recorded in PhotoCraft saves as; `T ` takes the property's class.
fn canonical(scale: &Scale) -> Descriptor {
let t = desc("measurementScale")
.with("pixelLength", D::Integer(scale.pixels))
.with("logicalLength", D::Double(scale.logical))
.with("logicalUnits", text(&scale.units));
desc("null").with("null", target()).with("T ", D::Descriptor(t))
}
/// Map the measured form; any other stays a complete kept step.
pub(super) fn from(d: &Descriptor) -> Mapped {
let Some(scale) = recorded(d) else { return Mapped::Unsupported { harmless: false } };
let mut p = json!({"preset": "custom", "pixelLength": scale.pixels, "logicalLength": scale.logical, "units": scale.units});
if *d != canonical(&scale) {
p[SOURCE] = photocraft_paint::tile::b64_encode(&d.to_bytes()).into();
}
step(SET_SCALE, p)
}
/// A native step the event holds: a custom scale with all three values given, a whole pixel
/// length (the event stores a long) and units that aren't blank. A step that reads the scale
/// (no params), resets it to the default or leaves a value to the document's current scale
/// refuses export: the event can't say any of those.
fn native(p: &Value) -> Option<Scale> {
let m = p.as_object()?;
if m.keys().any(|key| !["preset", "pixelLength", "logicalLength", "units", "logicalUnits", SOURCE].contains(&key.as_str())) {
return None;
}
if !matches!(m.get("preset"), None | Some(Value::Null)) && jstr(p, "preset") != Some("custom") {
return None;
}
let pixels = m.get("pixelLength")?.as_f64().filter(|v| v.is_finite() && *v > 0.0 && v.fract() == 0.0 && *v <= f64::from(i32::MAX))?;
let logical = m.get("logicalLength")?.as_f64().filter(|v| v.is_finite() && *v > 0.0)?;
// The native command reads `units`, else `logicalUnits`.
let units = m.get("units").or_else(|| m.get("logicalUnits")).and_then(Value::as_str).filter(|u| !u.trim().is_empty())?;
Some(Scale { pixels: pixels as i32, logical, units: units.to_string() })
}
/// Save the recorded descriptor while the step still sets the same scale, otherwise the
/// canonical form of the step's settings.
pub(super) fn to(p: &Value) -> Option<Descriptor> {
let scale = native(p)?;
let source = jstr(p, SOURCE)
.and_then(photocraft_paint::tile::b64_decode)
.and_then(|bytes| Descriptor::from_bytes(&bytes).ok())
.filter(|d| recorded(d).as_ref() == Some(&scale));
Some(source.unwrap_or_else(|| canonical(&scale)))
}
+7 -3
View File
@@ -858,6 +858,7 @@ fn every_mapped_command_exports_and_imports_back() {
("type.loadDefaultTypeStyles", json!({})),
("type.saveDefaultTypeStyles", json!({})),
("image.analysis.recordMeasurements", json!({})),
("image.analysis.setMeasurementScale", json!({"preset": "custom", "pixelLength": 120, "logicalLength": 2.5, "units": "mm"})),
("layer.videoLayers.insertBlankFrame", json!({})),
("layer.videoLayers.duplicateFrame", json!({})),
("layer.videoLayers.deleteFrame", json!({})),
@@ -3832,13 +3833,16 @@ fn loaded_camera_raw_filter_steps_save_back_unchanged() {
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()))
saved.actions[0].items.first().map(|i| (i.event.clone(), i.dictionary.clone(), i.descriptor.clone()))
};
// Strict save, and the Actions panel's save (which skips what can't be written).
// Strict save, and the Actions panel's save (which skips what can't be written). The step's
// dictionary is stored action data, so it keeps Photoshop's wording and not the menu label
// ("RAW Develop Filter"): a loaded step reads the same in Photoshop's Actions panel.
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()))));
let expected = (AtnEvent::name("Adobe Camera Raw Filter"), b"Camera Raw Filter".to_vec(), Some(recorded.clone()));
assert_eq!(saved_step(&r), Some(expected));
}
// It plays.
s.execute("file.new", json!({"width": 16, "height": 12})).unwrap();
@@ -0,0 +1,132 @@
//! The Background Eraser on a layer with Lock transparent pixels on (#11905): the reference
//! application erases to transparency exactly as on an unlocked layer, leaves the lock on and shows
//! no alert. Lock image pixels and Lock all still refuse; the Eraser and the Magic Eraser keep their
//! own lock behaviour (they paint the background colour).
use super::*;
/// White Background plus a normal layer "Target" with a solid red band across it (y 10..30).
fn session(depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 40, "depth": depth})).unwrap();
s.execute("layer.new.layer", json!({"name": "Target"})).unwrap();
s.execute("select.rect", json!({"x": 0, "y": 10, "width": 64, "height": 20, "antiAlias": false})).unwrap();
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s
}
fn target(s: &Session) -> &Layer {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap()
}
fn alphas(s: &Session) -> Vec<f32> {
let surf = target(s).surface().unwrap();
(0..40).flat_map(|y| (0..64).map(move |x| (x, y))).map(|(x, y)| surf.rgba(x, y)[3]).collect()
}
fn click() -> Value {
json!({"points": [[32, 20]], "size": 20, "hardness": 1, "tolerance": 50})
}
#[test]
fn a_click_on_a_transparency_locked_layer_erases_as_on_an_unlocked_one() {
for depth in [8, 16, 32] {
let mut free = session(depth);
free.execute("paint.backgroundEraser", click()).unwrap();
let want = alphas(&free);
let mut s = session(depth);
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
let h = s.active().unwrap().history.past_len();
s.execute("paint.backgroundEraser", click()).unwrap();
assert_eq!(s.active().unwrap().history.past_len(), h + 1, "{depth}-bit: one History step");
assert_eq!(target(&s).surface().unwrap().rgba(32, 20)[3], 0.0, "{depth}-bit: erased to transparency");
assert_eq!(alphas(&s), want, "{depth}-bit: the same alpha as on an unlocked layer");
assert!(target(&s).locks.transparency, "{depth}-bit: the lock stays on");
assert_eq!(target(&s).name, "Target", "{depth}-bit: the same layer");
}
}
#[test]
fn a_drag_and_the_live_preview_erase_a_transparency_locked_layer_too() {
let mut s = session(8);
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
let opts = |pts: &[[f64; 2]]| json!({"points": pts, "size": 12, "hardness": 1});
let all = [[8.0, 20.0], [32.0, 20.0], [56.0, 20.0]];
let mut live = live_background_eraser(&s, &opts(&all[..1])).unwrap();
for q in &all[1..] {
live.push(&[photocraft_paint::StrokePoint::new(q[0], q[1], 1.0)]).unwrap();
}
let id = s.active().unwrap().active_layer.unwrap();
let shown = live.doc.layer(id).unwrap().surface().unwrap().clone();
s.execute("paint.backgroundEraser", opts(&all)).unwrap();
let surf = target(&s).surface().unwrap();
for x in [8, 32, 56] {
assert_eq!(surf.rgba(x, 20)[3], 0.0, "({x}, 20) erased");
assert_eq!(shown.rgba(x, 20)[3], 0.0, "the preview shows ({x}, 20) erased");
}
assert_eq!(surf.rgba(32, 5)[3], 0.0, "transparent pixels stay transparent");
assert!(target(&s).locks.transparency);
}
#[test]
fn with_a_colour_channel_target_the_preview_matches_the_commit_on_a_locked_layer() {
// A channel target erases colour channels only (towards the background colour) and never
// changes alpha. The commit mixes back without the lock, so the preview must too: at 32 bits
// a lock-keeping mix rounds partly transparent pixels differently. The stroke crosses the
// band's edge and a half-transparent strip, at half opacity, so every mix case is under the tip.
for depth in [8, 16, 32] {
let mut s = session(depth);
s.execute("select.rect", json!({"x": 0, "y": 4, "width": 64, "height": 6, "antiAlias": false})).unwrap();
s.execute("edit.fill", json!({"color": "#3a7fd0", "opacity": 37})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
let opts = |pts: &[[f64; 2]]| json!({"points": pts, "size": 16, "hardness": 0.5, "opacity": 0.53, "target": {"colors": [1]}});
let all = [[8.0, 9.0], [32.0, 10.0], [56.0, 11.0]];
let mut live = live_background_eraser(&s, &opts(&all[..1])).unwrap();
for q in &all[1..] {
live.push(&[photocraft_paint::StrokePoint::new(q[0], q[1], 1.0)]).unwrap();
}
let id = s.active().unwrap().active_layer.unwrap();
let shown = live.doc.layer(id).unwrap().surface().unwrap().clone();
let before = alphas(&s);
s.execute("paint.backgroundEraser", opts(&all)).unwrap();
let surf = target(&s).surface().unwrap();
assert!(surf.rgba(32, 12)[1] > 0.0, "{depth}-bit: the green channel moved towards the white background");
for (x, y) in (0..40).flat_map(|y| (0..64).map(move |x| (x, y))) {
assert_eq!(shown.rgba(x, y), surf.rgba(x, y), "{depth}-bit ({x}, {y}): preview = commit");
}
assert_eq!(alphas(&s), before, "{depth}-bit: alpha untouched");
}
}
#[test]
fn locked_pixels_and_lock_all_still_refuse() {
for locks in [json!({"pixels": true}), json!({"all": true})] {
let mut s = session(8);
s.execute("layer.setProps", json!({"locks": locks})).unwrap();
let before = alphas(&s);
let h = s.active().unwrap().history.past_len();
let err = s.execute("paint.backgroundEraser", click()).unwrap_err().to_string();
assert!(err.contains("Could not complete your request because the layer \"Target\" is locked"), "{locks}: {err}");
assert!(live_background_eraser(&s, &click()).is_err(), "{locks}: the preview refuses too");
assert_eq!(alphas(&s), before, "{locks}: nothing erased");
assert_eq!(s.active().unwrap().history.past_len(), h, "{locks}: no History step");
}
}
#[test]
fn the_eraser_and_the_magic_eraser_keep_painting_the_background_colour() {
// Magic Eraser: the background colour (white by default), still opaque.
let mut s = session(8);
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
s.execute("paint.magicEraser", json!({"x": 32, "y": 20})).unwrap();
assert_eq!(target(&s).surface().unwrap().rgba(32, 20), [1.0, 1.0, 1.0, 1.0]);
// Eraser: the same.
let mut s = session(8);
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
s.execute("paint.stroke", json!({"erase": true, "points": [[8, 20], [56, 20]], "size": 8, "hardness": 1.0})).unwrap();
assert_eq!(target(&s).surface().unwrap().rgba(32, 20), [1.0, 1.0, 1.0, 1.0]);
}
+30 -2
View File
@@ -832,6 +832,21 @@ fn mixer_load_pixel(s: &mut Session, p: &Value) -> Result<Value> {
/// channel or Quick Mask `target` is refused rather than recolouring the layer instead.
fn color_replacement_setup(s: &Session, p: &Value) -> Result<(Stroke, ReplaceSettings, photocraft_doc::LayerId)> {
let cmd = "paint.colorReplacement";
// The modes and depths the reference application refuses, with its words (#11923). The live
// stroke runs this setup too, so it previews nothing in them. 32-bit Grayscale, CMYK and Lab,
// Multichannel and Duotone weren't measured and keep painting.
if let Some(st) = s.active() {
use photocraft_color::{ColorMode, SampleType};
let why = match (st.doc.mode, st.doc.depth) {
(ColorMode::Indexed, _) => Some("it does not work with Indexed Color images (convert image to RGB Color mode to edit)."),
(ColorMode::Bitmap, _) | (ColorMode::Grayscale, SampleType::U8 | SampleType::U16) => Some("it only works in full color modes."),
(ColorMode::Rgb, SampleType::F32) => Some("it does not work with 32 bit per channel images (convert image to 8 or 16 bit per channel to edit)."),
_ => None,
};
if let Some(why) = why {
return Err(EngineError::Other(format!("Could not use the Color Replacement tool because {why}")));
}
}
if let Some(t) = p.get("target").filter(|t| t.as_str() != Some("pixels"))
&& crate::color_channels::explicit(p, s.active().map_or(0, |st| crate::channel_cmds::color_count(&st.doc)))?.is_none()
{
@@ -855,9 +870,14 @@ fn color_replacement_setup(s: &Session, p: &Value) -> Result<(Stroke, ReplaceSet
Ok((Stroke { brush, points: pts }, rs, id))
}
/// The History state (and recorded step) name of a Color Replacement edit.
pub const COLOR_REPLACEMENT_STEP: &str = "Color Replacement Tool";
fn color_replacement(s: &mut Session, p: &Value) -> Result<Value> {
let (stroke, rs, id) = color_replacement_setup(s, p)?;
let dmg = s.edit("Color Replacement", |doc, _| {
// The reference application names every click, stroke and Shift+click segment "Color
// Replacement Tool" (#11933); the command's label is the same, so recorded actions match.
let dmg = s.edit(COLOR_REPLACEMENT_STEP, |doc, _| {
let sel = doc.selection.clone();
let lock = doc.effective_locks(id).transparency;
let surf = paint_surface(doc, id, &json!({}))?;
@@ -1340,7 +1360,7 @@ pub fn specs() -> Vec<CommandSpec> {
),
spec!(
"paint.colorReplacement",
"Color Replacement",
"Color Replacement Tool",
r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":0..100=30,"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"target":"pixels"="pixels","seed":u64?}"##,
crate::commands::has_paintable,
color_replacement,
@@ -1381,5 +1401,13 @@ pub fn specs() -> Vec<CommandSpec> {
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "color_replacement_modes_tests.rs"]
mod color_replacement_modes_tests;
#[cfg(test)]
mod mixer_live_tests;
#[cfg(test)]
#[path = "color_replacement_history_name_tests.rs"]
mod color_replacement_history_name_tests;
@@ -151,6 +151,7 @@ impl LiveMixer {
/// Validate the params and capture the document and paint load, without rendering a dab.
fn prepare(s: &Session, p: &Value, preview_limits: bool) -> Result<(Self, Vec<StrokePoint>)> {
mode_refusal(s)?;
let captured = crate::channel_cmds::inject_target(s, CMD, p.clone());
let p = &captured;
has_paintable(s).map_err(EngineError::Other)?;
@@ -330,9 +331,26 @@ impl LiveMixer {
}
}
/// The reference's alert for a Mixer Brush press in an Indexed Color document (#11958).
pub const INDEXED_REFUSAL: &str =
"Could not use the Mixer Brush tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit).";
/// The reference's alert for a Mixer Brush press in a Bitmap document (#11958).
pub const BITMAP_REFUSAL: &str = "Could not use the Mixer Brush tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).";
/// The Mixer Brush refuses Indexed Color and Bitmap documents before anything is painted, with the
/// reference's alert text; other modes (Duotone and Multichannel were not measured) paint as before.
fn mode_refusal(s: &Session) -> Result<()> {
match s.active().map(|st| st.doc.mode) {
Some(photocraft_color::ColorMode::Indexed) => Err(EngineError::Other(INDEXED_REFUSAL.into())),
Some(photocraft_color::ColorMode::Bitmap) => Err(EngineError::Other(BITMAP_REFUSAL.into())),
_ => Ok(()),
}
}
/// Consume a matching prepared result or replay without the preview tile cap, then commit one history step.
/// The completed stroke also applies the automatic clean/load settings to the stored paint load.
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
mode_refusal(s)?;
let points = parse_points(p, CMD)?;
let cached =
s.live_commit.take().filter(|live| live.matches(s, CMD, p, &points) && live.mixer.as_ref().is_some_and(|(before, _)| *before == s.tools.mixer));
+18 -2
View File
@@ -899,7 +899,9 @@ fn ink_surface(s: &Surface, d: &Duotone) -> Surface {
}
/// Image › Mode › RGB/Grayscale/CMYK/Lab through the CMS. Params: `profile` (destination,
/// default the mode's working profile), `intent` (default relative), `bpc` (default true).
/// default the mode's working profile; Indexed→RGB without an explicit profile instead expands
/// the already-RGB storage without changing its encoded samples or ICC bytes), `intent`
/// (default relative), `bpc` (default true).
pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value> {
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
if doc.mode == ColorMode::Multichannel && mode != ColorMode::Multichannel {
@@ -908,8 +910,13 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value
if doc.mode == mode && p.get("profile").is_none() {
return Ok(Value::Null);
}
let preserve_indexed_rgb = p.get("profile").and_then(Value::as_str).is_none()
&& doc.mode == ColorMode::Indexed
&& mode == ColorMode::Rgb
&& doc.icc_profile.as_ref().is_none_or(|bytes| profile_from_bytes(bytes).ok().is_some_and(|p| p.color_space == ColorSpace::Rgb));
let dst = match p.get("profile").and_then(Value::as_str) {
Some(spec) => s.color.resolve(spec, Some(doc), Some(mode))?,
None if preserve_indexed_rgb => document_profile(doc),
None => s.color.working(mode),
};
if space_mode(dst.color_space)
@@ -923,7 +930,16 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value
}
let intent = intent_or(p, s.color.settings.intent())?;
let bpc = bool_param(p, "bpc", s.color.settings.bpc);
s.edit("Mode Change", |doc, _| convert_document(doc, &dst, intent, bpc))?;
if preserve_indexed_rgb {
s.edit("Mode Change", |doc, _| {
doc.mode = ColorMode::Rgb;
doc.color_table = None;
doc.duotone = None;
Ok(())
})?;
} else {
s.edit("Mode Change", |doc, _| convert_document(doc, &dst, intent, bpc))?;
}
Ok(json!({ "profile": dst.description, "intent": intent.id(), "bpc": bpc }))
}
@@ -0,0 +1,45 @@
//! #11933: a Color Replacement click, a drag and a Shift+click segment each add one History state
//! named "Color Replacement Tool", on a layer and on the Background with Lock transparent pixels;
//! the command's label, which recorded actions show, is the same name.
use serde_json::json;
use super::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
s.execute("tools.setColors", json!({"foreground": "#0000ff"})).unwrap();
s
}
fn last(s: &Session) -> (usize, Option<String>) {
let h = &s.active().unwrap().history;
(h.past_len(), h.entries().last().map(|e| e.to_string()))
}
#[test]
fn every_click_stroke_and_segment_is_one_color_replacement_tool_state() {
for on_background in [false, true] {
let mut s = session();
if !on_background {
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("edit.fill", json!({"color": "#dc1e1e"})).unwrap();
} else {
s.execute("edit.fill", json!({"color": "#dc1e1e"})).unwrap();
s.execute("layer.lockLayers", json!({"transparency": true})).unwrap();
}
for points in [json!([[20, 20]]), json!([[20, 50], [80, 50]]), json!([[80, 50], [80, 80]])] {
let (n, _) = last(&s);
s.execute("paint.colorReplacement", json!({"points": points, "size": 15})).unwrap();
assert_eq!(last(&s), (n + 1, Some(COLOR_REPLACEMENT_STEP.to_string())), "{points} (background {on_background})");
}
}
assert_eq!(COLOR_REPLACEMENT_STEP, "Color Replacement Tool");
}
#[test]
fn recorded_steps_use_the_same_name() {
let spec = crate::commands::find("paint.colorReplacement").expect("the command");
assert_eq!(spec.label, COLOR_REPLACEMENT_STEP);
}
@@ -0,0 +1,71 @@
//! #11923: the Color Replacement tool refuses RGB/32, Grayscale, Bitmap and Indexed documents with
//! the reference application's messages, painting nothing and adding no history; the live stroke
//! is refused the same way. RGB/8, RGB/16, CMYK and Lab paint.
use photocraft_color::{Color, ColorMode, SampleType};
use photocraft_doc::{Document, Size};
use serde_json::json;
use super::*;
const DEPTH_32: &str =
"Could not use the Color Replacement tool because it does not work with 32 bit per channel images (convert image to 8 or 16 bit per channel to edit).";
const NOT_FULL_COLOR: &str = "Could not use the Color Replacement tool because it only works in full color modes.";
const INDEXED: &str = "Could not use the Color Replacement tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit).";
/// A session with one 64 × 64 document of `mode` and `depth`, filled red.
fn session(mode: ColorMode, depth: SampleType) -> Session {
let mut s = Session::new();
s.add_document(Document::with_background("t", Size::new(64, 64), mode, depth, Color::rgb(220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0)), None);
s.tools.foreground = [0.0, 0.0, 1.0, 1.0];
s
}
fn stroke() -> Value {
json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100})
}
fn steps(s: &Session) -> usize {
s.active().unwrap().history.past_len()
}
fn pixels(s: &Session) -> Vec<f32> {
let st = s.active().unwrap();
let surf = st.doc.layers[0].surface().unwrap();
(0..64).flat_map(|y| (0..64).flat_map(move |x| surf.pixel(x, y))).collect()
}
#[test]
fn refused_modes_say_why_and_paint_nothing() {
for (mode, depth, want) in [
(ColorMode::Rgb, SampleType::F32, DEPTH_32),
(ColorMode::Grayscale, SampleType::U8, NOT_FULL_COLOR),
(ColorMode::Grayscale, SampleType::U16, NOT_FULL_COLOR),
(ColorMode::Bitmap, SampleType::U8, NOT_FULL_COLOR),
(ColorMode::Indexed, SampleType::U8, INDEXED),
] {
let mut s = session(mode, depth);
let (before, n) = (pixels(&s), steps(&s));
let err = s.execute("paint.colorReplacement", stroke()).unwrap_err().to_string();
assert_eq!(err, want, "{mode:?}/{depth:?}");
assert_eq!(pixels(&s), before, "{mode:?}/{depth:?}: nothing painted");
assert_eq!(steps(&s), n, "{mode:?}/{depth:?}: no history");
// The live stroke previews nothing either.
let live = live_color_replacement(&s, &stroke()).err().map(|e| e.to_string());
assert_eq!(live.as_deref(), Some(want), "{mode:?}/{depth:?}: live");
}
}
#[test]
fn full_colour_documents_still_paint() {
for (mode, depth) in
[(ColorMode::Rgb, SampleType::U8), (ColorMode::Rgb, SampleType::U16), (ColorMode::Cmyk, SampleType::U8), (ColorMode::Lab, SampleType::U8)]
{
let mut s = session(mode, depth);
let (before, n) = (pixels(&s), steps(&s));
s.execute("paint.colorReplacement", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}"));
assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: painted");
assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}");
assert!(live_color_replacement(&s, &stroke()).is_ok(), "{mode:?}/{depth:?}: live");
}
}
@@ -0,0 +1,100 @@
//! #11763: each Count tool edit gets the reference application's History name. A `count.setGroup`
//! that changes exactly one field takes that field's name; several fields at once, or a switch of
//! the current group, keep "Count Group Options".
use serde_json::{Value, json};
use crate::Session;
/// A 100 × 100 document with one count group holding one marker at 10,10 (its first state is
/// "Add Count Object").
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
s.execute("count.add", json!({"x": 10, "y": 10})).unwrap();
s
}
fn steps(s: &Session) -> usize {
s.active().unwrap().history.past_len()
}
/// Run `id` and return the History name of the one step it added.
fn named(s: &mut Session, id: &str, p: Value) -> String {
let before = steps(s);
s.execute(id, p.clone()).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
assert_eq!(steps(s), before + 1, "{id} {p} adds exactly one step");
s.active().unwrap().history.undo_label().unwrap_or_default().to_string()
}
#[test]
fn marker_edits_are_add_drag_and_delete_count_object() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
// The first click makes "Count Group 1" too, still one "Add Count Object" step.
assert_eq!(named(&mut s, "count.add", json!({"x": 10, "y": 10})), "Add Count Object");
assert_eq!(named(&mut s, "count.add", json!({"x": 40, "y": 40})), "Add Count Object");
assert_eq!(named(&mut s, "count.move", json!({"x": 10, "y": 10, "to": [20, 20]})), "Drag Count Object");
assert_eq!(named(&mut s, "count.remove", json!({"x": 40, "y": 40})), "Delete Count Object");
}
#[test]
fn group_edits_keep_or_take_their_names() {
let mut s = session();
assert_eq!(named(&mut s, "count.newGroup", json!({"name": "Leaves"})), "Add Count Group");
assert_eq!(named(&mut s, "count.clear", json!({})), "Clear Count");
assert_eq!(named(&mut s, "count.deleteGroup", json!({})), "Delete Count Group");
}
#[test]
fn a_single_field_change_uses_that_fields_name() {
for (p, want) in [
(json!({"name": "Seeds"}), "Set Count Group Name"),
(json!({"visible": false}), "Set Count Group Visibility"),
(json!({"color": "#204080"}), "Set Count Draw Color"),
(json!({"markerSize": 5}), "Set Count Marker Size"),
(json!({"labelSize": 20}), "Set Count Font Size"),
] {
let mut s = session();
assert_eq!(named(&mut s, "count.setGroup", p.clone()), want, "{p}");
}
}
#[test]
fn several_fields_at_once_keep_count_group_options() {
let mut s = session();
assert_eq!(named(&mut s, "count.setGroup", json!({"markerSize": 5, "labelSize": 20})), "Count Group Options");
// A field sent with its current value doesn't count as a change.
let mut s = session();
let name = s.execute("image.analysis.countTool", json!({})).unwrap()["groups"][0]["name"].clone();
assert_eq!(named(&mut s, "count.setGroup", json!({"name": name, "markerSize": 6})), "Set Count Marker Size");
}
#[test]
fn switching_the_current_group_keeps_todays_name() {
let mut s = session();
s.execute("count.newGroup", json!({"name": "Two"})).unwrap();
assert_eq!(named(&mut s, "count.setGroup", json!({"group": 0})), "Count Group Options", "only `group`");
assert_eq!(named(&mut s, "count.setGroup", json!({"group": 1, "active": true})), "Count Group Options", "`active: true`, no field change");
// A field change together with a switch is two changes: today's name too.
assert_eq!(named(&mut s, "count.setGroup", json!({"group": 0, "active": true, "visible": false})), "Count Group Options");
}
#[test]
fn no_change_adds_no_step_and_bad_params_stay_errors() {
let mut s = session();
let before = steps(&s);
// The current group's own values: nothing changes, no step.
s.execute("count.setGroup", json!({"group": 0})).unwrap();
assert_eq!(steps(&s), before);
for (id, p) in [
("count.setGroup", json!({"group": 9, "name": "x"})),
("count.setGroup", json!({"markerSize": 2.5})),
("count.move", json!({"x": 90, "y": 90, "to": [1, 1]})),
("count.remove", json!({"x": 90, "y": 90})),
("count.add", json!({"x": 1, "y": 1, "group": 7})),
] {
assert!(s.execute(id, p.clone()).is_err(), "{id} {p}");
assert_eq!(steps(&s), before, "{id} {p} adds no step");
}
}
@@ -0,0 +1,52 @@
//! #11775: Record Measurements labels a Count tool row "Count N"; selection and ruler rows keep
//! their labels, and N is the number the row gets today (the shared counter).
use serde_json::{Value, json};
use crate::Session;
fn five_counts() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
for i in 0..5 {
s.execute("count.add", json!({"x": 10 + 10 * i, "y": 10})).unwrap();
}
s
}
fn record(s: &mut Session, source: &str) -> Value {
let r = s.execute("image.analysis.recordMeasurements", json!({"source": source})).unwrap();
let rows = r["rows"].as_array().unwrap();
assert_eq!(rows.len(), 1, "{source}: {r}");
rows[0]["values"].clone()
}
#[test]
fn a_count_row_is_labelled_count_n() {
for source in ["count", "auto"] {
let mut s = five_counts();
let row = record(&mut s, source);
assert_eq!(row["label"], json!("Count 1"), "{source}: {row}");
assert_eq!(row["count"], json!(5), "{source}: {row}");
assert_eq!(row["source"], json!("Count Tool"), "{source}: {row}");
}
}
#[test]
fn other_rows_keep_their_labels_and_the_counter_is_shared() {
let mut s = five_counts();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
let selection = record(&mut s, "selection");
assert_eq!(selection["label"], json!("Measurement 1"), "{selection}");
let count = record(&mut s, "count");
assert_eq!(count["label"], json!("Count 2"), "{count}");
// `auto` picks the selection over the counts, and keeps its label.
let auto = record(&mut s, "auto");
assert_eq!(auto["source"], json!("Selection"), "{auto}");
assert_eq!(auto["label"], json!("Measurement 3"), "{auto}");
s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [3, 4]})).unwrap();
let ruler = record(&mut s, "ruler");
assert_eq!(ruler["label"], json!("Measurement 4"), "{ruler}");
let count = record(&mut s, "count");
assert_eq!(count["label"], json!("Count 5"), "{count}");
}
+1 -1
View File
@@ -435,7 +435,7 @@ fn perspective(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
}
pub fn specs() -> Vec<CommandSpec> {
const L: &str = r##"{"strokes":[{"tool":"forwardWarp|reconstruct|smooth|twirlCw|twirlCcw|pucker|bloat|pushLeft|freeze|thaw|lassoMask|reconstructAll","size":px=100,"density":0-100=50,"pressure":0-100=100,"rate":0-100=80,"points":[[x,y,pressure?]…],"amount":%? (twirlCcw: twirlCw reversed, what an Alt-drag with Twirl Clockwise records; reconstructAll; lassoMask: 1 freezes the polygon in points, 0 thaws it)}…],"meshSize":px? (field resolution, px per node; default 2, or 4 above 4 MP),"layer":id?} — strokes replay in order on a fresh field; a selection limits the effect; on a smart object it becomes a smart filter"##;
const L: &str = r##"{"strokes":[{"tool":"forwardWarp|reconstruct|smooth|twirlCw|twirlCcw|pucker|bloat|pushLeft|freeze|thaw|lassoMask|reconstructAll","size":px=100,"density":0-100=50,"pressure":0-100=100,"rate":0-100=80,"points":[[x,y,pressure?,ms?]…] (ms: milliseconds since the previous point; a point with it follows the pointer exactly and times the stationary tools in real time, as the dialog records them),"amount":%? (twirlCcw: twirlCw reversed, what an Alt-drag with Twirl Clockwise records; reconstructAll; lassoMask: 1 freezes the polygon in points, 0 thaws it)}…],"meshSize":px? (field resolution, px per node; default 2, or 4 above 4 MP),"layer":id?} — strokes replay in order on a fresh field; a selection limits the effect; on a smart object it becomes a smart filter"##;
const P: &str = r##"{"pins":[{"src":[x,y],"dst":[x,y],"rotate":deg?,"depth":n?}…],"mode":"rigid|normal|distort"="normal","density":"fewer|normal|more"="normal","expansion":px=2,"interpolation":"bicubic|bilinear|nearest","layer":id?} — mesh over the opaque region, as-rigid-as-possible; on a smart object it becomes a smart filter"##;
const Q: &str = r##"{"planes":[{"src":[[x,y]×4],"dst":[[x,y]×4]}…] (corners clockwise from top-left; corners that coincide in src are linked),"straighten":"horizontal|vertical|auto"?,"interpolation":"bicubic|bilinear|nearest","layer":id?}"##;
vec![
+2 -2
View File
@@ -1267,8 +1267,8 @@ pub fn specs() -> Vec<CommandSpec> {
has_clip,
|s, p| paste(s, p, true)
),
spec!("layer.new.layerViaCopy", "Layer via Copy", &["Layer", "New"], Some("Cmd+J"), "{}", has_doc, |s, _| layer_via(s, false)),
spec!("layer.new.layerViaCut", "Layer via Cut", &["Layer", "New"], Some("Cmd+Shift+J"), "{}", has_pixels, |s, _| layer_via(s, true)),
spec!("layer.new.layerViaCopy", "Layer Via Copy", &["Layer", "New"], Some("Cmd+J"), "{}", has_doc, |s, _| layer_via(s, false)),
spec!("layer.new.layerViaCut", "Layer Via Cut", &["Layer", "New"], Some("Cmd+Shift+J"), "{}", has_pixels, |s, _| layer_via(s, true)),
spec!("layer.mergeVisible", "Merge Visible", &["Layer"], Some("Cmd+Shift+E"), "{}", has_doc, |s, _| merge_visible(s)),
spec!("image.autoTone", "Auto Tone", &["Image"], Some("Cmd+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "tone")),
spec!("image.autoContrast", "Auto Contrast", &["Image"], Some("Cmd+Alt+Shift+L"), "{}", has_pixels, |s, _| auto_adjust(s, "contrast")),
+28 -11
View File
@@ -4,10 +4,12 @@
//!
//! Like Photoshop, both turn a Background layer into a normal layer ("Layer 0") first, since the
//! Background can't hold transparency. The Magic Eraser paints the background colour on other
//! layers with locked transparency; the Background Eraser refuses them. Both respect the selection,
//! work in the layer's own colour model and depth, and are one undo step per click / stroke.
//! layers with locked transparency; the Background Eraser erases them to transparency and leaves
//! the lock on. Both respect the selection, work in the layer's own colour model and depth, and are
//! one undo step per click / stroke.
use photocraft_algo::selection as sel;
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::{Document, Layer, LayerContent, LayerId};
use photocraft_geom::Rect;
use photocraft_paint::Stroke;
@@ -105,7 +107,10 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result<Value> {
let surf = d.doc.layer(id).and_then(Layer::surface).ok_or(EngineError::NoLayer(id))?;
(d.doc.bounds(), sel::rgba8_image(surf, d.doc.bounds()))
};
let region = sel::wand_region(&img, area, (x, y), tolerance, contiguous, anti_alias);
// The reference's colour distance is measured for 8-bit RGB only (#11995).
let rgb8 = s.active().is_some_and(|d| d.doc.mode == ColorMode::Rgb && d.doc.depth == SampleType::U8);
let distance = if rgb8 { sel::ColorDistance::Spread } else { sel::ColorDistance::LargestChannel };
let region = sel::wand_region_by(&img, area, (x, y), tolerance, contiguous, anti_alias, None, distance);
drop(img);
let Some(region) = region else { return Ok(damage(s, Rect::EMPTY, false)) };
let bg = s.tools.background;
@@ -148,12 +153,11 @@ fn background_eraser_setup(s: &Session, p: &Value) -> Result<(Stroke, BgEraseSet
let id = active_pixel_layer(s, p, CMD)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
// Lock transparent pixels is no refusal: the reference application erases to transparency
// anyway and leaves the lock on.
if let Some(e) = pixels_locked(&d.doc, l) {
return Err(e);
}
if d.doc.effective_locks(id).transparency && !d.doc.is_background(id) && crate::color_channels::target(s, p)?.is_none() {
return Err(EngineError::Other(format!("Could not use the Background Eraser because the transparency of layer \"{}\" is locked", l.name)));
}
Ok((Stroke { brush, points: pts }, bs, id))
}
@@ -234,19 +238,27 @@ pub fn live_background_eraser(s: &Session, p: &Value) -> Result<crate::retouch_c
if colors.is_none() {
crate::extra_cmds::background_to_layer(&mut doc, id);
}
let stroke = background_eraser_stroke(&stroke);
let mut stroke = background_eraser_stroke(&stroke);
// The commit mixes back without the transparency lock (a locked layer is erased too, and a
// channel target leaves alpha alone), so the preview does as well; the points go in once the
// lock is off.
let points = std::mem::take(&mut stroke.points);
if let Some(colors) = colors {
return crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({"target":colors.params()}), stroke, Some(id), 0, |pre| {
let mut live = crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({"target":colors.params()}), stroke, Some(id), 0, |pre| {
selected_background_effect(pre, &bs, colors, bg)
})?
.with_tail_preview();
.unlocked();
live.push(&points)?;
return live.with_tail_preview();
}
crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({}), stroke, Some(id), 0, |pre| match background_eraser_effect(pre, &bs) {
let mut live = crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({}), stroke, Some(id), 0, |pre| match background_eraser_effect(pre, &bs) {
Some(effect) => Box::new(effect),
// No alpha: the commit erases nothing either.
None => Box::new(|_: &mut photocraft_paint::retouch::Region, _: &photocraft_paint::retouch::Footprint| {}),
})?
.with_tail_preview()
.unlocked();
live.push(&points)?;
live.with_tail_preview()
}
/// Eraser-group command specs.
@@ -275,5 +287,10 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
#[cfg(test)]
mod magic_eraser_tolerance_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "background_eraser_transparency_lock_tests.rs"]
mod transparency_lock_tests;
@@ -0,0 +1,239 @@
//! #11995: on 8-bit RGB the Magic Eraser measures Tolerance by the spread of `{0, dR, dG, dB}`, so
//! opposite changes in two channels count double. The expected values are the reference
//! application's measurements from the issue; the stripes document is drawn at a tenth of the size.
use photocraft_algo::selection as sel;
use photocraft_geom::Rect;
use serde_json::{Value, json};
use crate::Session;
const SEED: [u8; 3] = [200, 40, 40];
/// `d` of the patch grid's columns.
const GRID: [i32; 8] = [20, 50, 80, 110, 140, 170, 200, 230];
fn hex([r, g, b]: [u8; 3]) -> String {
format!("#{r:02x}{g:02x}{b:02x}")
}
fn document(w: i32, h: i32, depth: u32, background: [u8; 3]) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": w, "height": h, "mode": "rgb", "depth": depth, "background": hex(background)})).unwrap();
s
}
fn fill(s: &mut Session, [x, y, w, h]: [i32; 4], color: [u8; 3]) {
s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h, "antiAlias": false})).unwrap();
s.execute("edit.fill", json!({"color": hex(color)})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
}
fn erase(s: &mut Session, x: i32, y: i32, options: Value) {
let mut p = json!({"x": x, "y": y, "antiAlias": false});
p.as_object_mut().unwrap().extend(options.as_object().unwrap().clone());
s.execute("paint.magicEraser", p).unwrap();
}
fn rgba(s: &Session, x: i32, y: i32) -> [f32; 4] {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)
}
fn erased(s: &Session, x: i32, y: i32) -> bool {
rgba(s, x, y)[3] == 0.0
}
/// Grey (100, 100, 100) with ten-pixel patches along the top: same-direction and opposite changes.
fn grey_patches(depth: u32) -> (Session, [(i32, [u8; 3], i32); 4]) {
let patches = [(10, [130, 100, 70], 60), (30, [130, 130, 100], 30), (50, [70, 130, 100], 60), (70, [70, 70, 70], 30)];
let mut s = document(90, 30, depth, [100, 100, 100]);
for (x, color, _) in patches {
fill(&mut s, [x, 10, 10, 10], color);
}
(s, patches)
}
/// Opposite changes count double and same-direction changes once (Tolerance 29, 30, 59, 60).
#[test]
fn opposite_channel_changes_count_double_around_a_grey_seed() {
for tolerance in [29, 30, 59, 60] {
let (mut s, patches) = grey_patches(8);
erase(&mut s, 0, 0, json!({"tolerance": tolerance, "contiguous": false}));
for (x, color, metric) in patches {
assert_eq!(erased(&s, x + 5, 15), tolerance >= metric, "tolerance {tolerance}, patch {color:?}");
}
}
}
fn grid_colour(row: usize, d: i32) -> [u8; 3] {
let [r, g, b] = SEED.map(i32::from);
let [r, g, b] = match row {
0 => [r - d, g, b],
1 => [r + d, g, b],
2 => [r, g + d, b],
3 => [r, g + d, b + d],
_ => [r - d, g + d, b + d],
};
[r, g, b].map(|v| v.clamp(0, 255) as u8)
}
/// The issue's patch grid around (200, 40, 40): `0` is erased and `x` kept, one row per Tolerance.
#[test]
fn the_patch_grid_matches_the_measured_table() {
const TABLE: [(i32, [&str; 5]); 7] = [
(30, ["0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "xxxxxxxx"]),
(40, ["0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "0xxxxxxx", "0xxxxxxx"]),
(60, ["00xxxxxx", "00000000", "00xxxxxx", "00xxxxxx", "0xxxxxxx"]),
(100, ["000xxxxx", "00000000", "000xxxxx", "000xxxxx", "00xxxxxx"]),
(150, ["00000xxx", "00000000", "00000xxx", "00000xxx", "00xxxxxx"]),
(200, ["00000000", "00000000", "0000000x", "0000000x", "000xxxxx"]),
(255, ["00000000", "00000000", "00000000", "00000000", "0000xxxx"]),
];
for (tolerance, rows) in TABLE {
let mut s = document(80, 60, 8, SEED);
for row in 0..5 {
for (col, d) in GRID.into_iter().enumerate() {
fill(&mut s, [col as i32 * 10, 10 + row as i32 * 10, 10, 10], grid_colour(row, d));
}
}
erase(&mut s, 0, 0, json!({"tolerance": tolerance, "contiguous": false}));
for (row, want) in rows.into_iter().enumerate() {
let got: String = (0..8).map(|col| if erased(&s, col * 10 + 5, 15 + row as i32 * 10) { '0' } else { 'x' }).collect();
assert_eq!(got, want, "tolerance {tolerance}, row {row}");
}
}
}
const RED: [u8; 3] = [220, 30, 30];
const GREEN: [u8; 3] = [30, 180, 60];
const BLUE: [u8; 3] = [40, 60, 220];
const PINK: [u8; 3] = [240, 120, 120];
const UPPER_RED: (i32, i32) = (10, 5);
const LOWER_RED: (i32, i32) = (10, 22);
const WHITE_GAP: (i32, i32) = (10, 15);
/// The stripes over eight blocks (200, 40 + 20·i, 40), with a white gap cutting the red stripe.
fn stripes() -> Session {
let mut s = document(80, 60, 8, [255, 255, 255]);
for (i, color) in [RED, GREEN, BLUE, PINK].into_iter().enumerate() {
fill(&mut s, [i as i32 * 20, 0, 20, 30], color);
}
fill(&mut s, [0, 14, 20, 2], [255, 255, 255]);
for i in 0..8u8 {
fill(&mut s, [i32::from(i) * 10, 30, 10, 30], [200, 40 + 20 * i, 40]);
}
s
}
fn erased_blocks(s: &Session) -> usize {
(0..8).take_while(|i| erased(s, i * 10 + 5, 45)).count()
}
/// Contiguous from block 0: the blocks go one by one, and green and blue survive even at 255.
#[test]
fn stripes_contiguous_from_block_zero() {
for (tolerance, blocks) in
[(0, 1), (10, 1), (19, 1), (20, 2), (21, 2), (39, 2), (40, 3), (41, 3), (60, 4), (100, 6), (140, 8), (160, 8), (200, 8), (255, 8)]
{
let mut s = stripes();
erase(&mut s, 5, 45, json!({"tolerance": tolerance}));
assert_eq!(erased_blocks(&s), blocks, "tolerance {tolerance}");
assert_eq!(8 - (0..8).filter(|i| !erased(&s, i * 10 + 5, 45)).count(), blocks, "tolerance {tolerance}: the erased blocks are consecutive");
assert_eq!(erased(&s, 70, 15), tolerance >= 140, "tolerance {tolerance}: pink, reached through blocks 6 and 7");
assert_eq!(erased(&s, UPPER_RED.0, UPPER_RED.1), tolerance == 255, "tolerance {tolerance}: upper red, reached through the white gap");
if tolerance == 41 || tolerance >= 60 {
assert!(erased(&s, LOWER_RED.0, LOWER_RED.1), "tolerance {tolerance}: lower red");
}
if tolerance < 30 {
assert!(!erased(&s, LOWER_RED.0, LOWER_RED.1), "tolerance {tolerance}: lower red");
}
assert!(!erased(&s, 30, 15), "tolerance {tolerance}: green is kept");
assert!(!erased(&s, 50, 15), "tolerance {tolerance}: blue is kept");
}
}
/// Non-contiguous from block 0: white goes from Tolerance 220; green and blue never do.
#[test]
fn stripes_non_contiguous_from_block_zero() {
let mut s = stripes();
erase(&mut s, 5, 45, json!({"tolerance": 150, "contiguous": false}));
assert_eq!(erased_blocks(&s), 8);
assert!(erased(&s, UPPER_RED.0, UPPER_RED.1) && erased(&s, LOWER_RED.0, LOWER_RED.1), "both reds");
assert!(erased(&s, 70, 15), "pink");
assert!(!erased(&s, WHITE_GAP.0, WHITE_GAP.1), "the white gap (metric 215) is kept");
assert!(!erased(&s, 30, 15) && !erased(&s, 50, 15), "green and blue");
let mut s = stripes();
erase(&mut s, 5, 45, json!({"tolerance": 220, "contiguous": false}));
assert!(erased(&s, WHITE_GAP.0, WHITE_GAP.1), "white is within 220");
assert!(!erased(&s, 30, 15) && !erased(&s, 50, 15), "green and blue");
}
/// The fringe uses the same distance: a neighbour the spread rejects is not fully erased, even
/// though every one of its channels is within the Tolerance.
#[test]
fn anti_alias_does_not_erase_a_neighbour_the_spread_rejects() {
let (mut s, _) = grey_patches(8);
erase(&mut s, 0, 0, json!({"tolerance": 32, "contiguous": false, "antiAlias": true}));
assert!(rgba(&s, 15, 15)[3] == 1.0, "the patch's inside is kept");
assert!(rgba(&s, 10, 15)[3] > 0.0, "(130, 100, 70) has spread 60, past Tolerance 32");
}
/// Depths the rule was not measured for keep comparing each channel on its own.
#[test]
fn sixteen_bit_keeps_the_per_channel_limit() {
let (mut s, patches) = grey_patches(16);
erase(&mut s, 0, 0, json!({"tolerance": 30, "contiguous": false}));
for (x, color, _) in patches {
assert!(erased(&s, x + 5, 15), "patch {color:?}");
}
}
/// The Magic Wand and the Paint Bucket share the fill and keep the per-channel limit.
#[test]
fn the_magic_wand_and_paint_bucket_keep_the_per_channel_limit() {
let (mut s, _) = grey_patches(8);
s.execute("select.magicWand", json!({"x": 0, "y": 0, "tolerance": 30, "contiguous": false, "antiAlias": false})).unwrap();
let selected = sel::mask_from_surface(s.active().unwrap().doc.selection.as_ref(), Rect::new(0, 0, 90, 30));
assert_eq!(selected[15 * 90 + 15], 1.0, "the wand takes (130, 100, 70) at 30");
let (mut s, _) = grey_patches(8);
s.execute("paint.bucket", json!({"x": 0, "y": 0, "tolerance": 30, "contiguous": false, "antiAlias": false, "color": "#ff00ff"})).unwrap();
let [r, g, b, _] = rgba(&s, 15, 15);
assert_eq!([r, g, b], [1.0, 0.0, 1.0], "the bucket fills (130, 100, 70) at 30");
}
/// A transparent seed still matches every transparent pixel, and alpha still limits the match.
#[test]
fn the_spread_keeps_the_transparent_and_alpha_handling() {
let area = Rect::new(0, 0, 3, 1);
let run = |img: [[u8; 4]; 3], tolerance| sel::wand_region_by(&img, area, (0, 0), tolerance, false, false, None, sel::ColorDistance::Spread).unwrap();
let region = run([[10, 20, 30, 0], [200, 0, 90, 0], [9, 9, 9, 255]], 0.0);
assert_eq!((region.at(1, 0), region.at(2, 0)), (1.0, 0.0), "hidden colours don't matter; visible pixels don't match");
let half = [[100, 100, 100, 200], [100, 100, 100, 100], [100, 100, 100, 170]];
let region = run(half, 30.0);
assert_eq!((region.at(1, 0), region.at(2, 0)), (0.0, 1.0), "alpha differences stay limited by the Tolerance");
}
/// The spread was measured on opaque colours only: a partly transparent seed or pixel keeps the
/// per-channel limit, in the match and in the anti-alias fringe.
#[test]
fn partly_transparent_colours_keep_the_per_channel_limit() {
let area = Rect::new(0, 0, 3, 1);
let run = |img: &[[u8; 4]; 3], distance, anti_alias| sel::wand_region_by(img, area, (0, 0), 30.0, false, anti_alias, None, distance).unwrap();
let opaque = [[100, 100, 100, 255], [130, 100, 70, 255], [9, 9, 9, 255]];
assert_eq!(run(&opaque, sel::ColorDistance::Spread, false).at(1, 0), 0.0, "opaque colours use the spread");
for img in [
[[100, 100, 100, 128], [130, 100, 70, 128], [160, 100, 40, 128]],
[[100, 100, 100, 255], [130, 100, 70, 250], [160, 100, 40, 250]],
[[100, 100, 100, 250], [130, 100, 70, 255], [160, 100, 40, 255]],
] {
assert_eq!(run(&img, sel::ColorDistance::Spread, false).at(1, 0), 1.0, "{img:?}: every channel is within 30");
assert!(run(&img, sel::ColorDistance::Spread, true).at(2, 0) > 0.0, "{img:?}: the third pixel gets a fringe");
assert_eq!(run(&img, sel::ColorDistance::Spread, true), run(&img, sel::ColorDistance::LargestChannel, true), "{img:?}: same fringe");
}
}
+3 -3
View File
@@ -230,11 +230,11 @@ fn background_eraser_fails_gracefully() {
] {
assert!(s.execute("paint.backgroundEraser", p.clone()).is_err(), "{p}");
}
// A normal layer with locked transparency is refused.
// A layer with locked pixels is refused.
s.execute("layer.new.layer", json!({})).unwrap();
let id = s.active().unwrap().active_layer.unwrap();
s.edit("lock", |doc, _| {
doc.layer_mut(id).unwrap().locks.transparency = true;
doc.layer_mut(id).unwrap().locks.pixels = true;
Ok(())
})
.unwrap();
@@ -319,7 +319,7 @@ fn live_background_eraser_matches_the_commit() {
fn live_background_eraser_refuses_what_the_command_refuses() {
let mut s = session("rgb", 8);
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap();
let p = json!({"points": [[20, 20]]});
assert!(live_background_eraser(&s, &p).is_err());
assert!(s.execute("paint.backgroundEraser", p).is_err());
+5 -32
View File
@@ -74,13 +74,9 @@ pub(crate) fn step_key(s: &Session, what: &str) -> String {
/// area, the pixels, and the selection coverage per pixel; results are blended back by coverage,
/// and transparency stays locked when the layer locks it. When `p` targets an alpha channel, the
/// Quick Mask or the layer mask (`Session::execute` fills that in from the Channels panel), that
/// grayscale surface is rewritten instead, as the core filters do (#935).
fn map_pixels(s: &mut Session, label: &str, p: &Value, f: impl FnOnce(Rect, &mut [[f32; 4]], &[f32])) -> Result<Value> {
map_pixels_in(s, label, p, false, f)
}
/// [`map_pixels`], or with `whole` the whole canvas: `f` still gets the selection coverage, and
/// every pixel takes its result in full.
/// grayscale surface is rewritten instead, as the core filters do (#935). With `whole` the whole
/// canvas is rewritten: `f` still gets the selection coverage, and every pixel takes its result
/// in full.
fn map_pixels_in(s: &mut Session, label: &str, p: &Value, whole: bool, f: impl FnOnce(Rect, &mut [[f32; 4]], &[f32])) -> Result<Value> {
let id = layer_param(s, p)?;
let channel = crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels;
@@ -275,27 +271,6 @@ fn equalize(s: &mut Session, p: &Value) -> Result<Value> {
})
}
/// Filter › Blur › Average: the selection (or layer) filled with its mean colour.
fn average(s: &mut Session, p: &Value) -> Result<Value> {
map_pixels(s, "Average", p, |_, px, cover| {
let (mut sum, mut wsum, mut asum, mut n) = ([0f64; 3], 0f64, 0f64, 0f64);
for (p, &k) in px.iter().zip(cover) {
let w = (p[3] * k) as f64;
for c in 0..3 {
sum[c] += p[c] as f64 * w;
}
wsum += w;
asum += (p[3] * k) as f64;
n += k as f64;
}
if wsum <= 0.0 {
return;
}
let avg = [(sum[0] / wsum) as f32, (sum[1] / wsum) as f32, (sum[2] / wsum) as f32, (asum / n.max(1e-9)) as f32];
px.fill(avg);
})
}
// ---------- transform presets ----------
/// The presets' params: like Free Transform, they follow the Channels and Layers panel target.
@@ -402,7 +377,6 @@ fn paste_into(s: &mut Session, p: &Value, outside: bool) -> Result<Value> {
let key = step_key(s, "pasteInto");
params["coalesce"] = json!(key);
params["target"] = json!("pixels");
let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
let r = s.execute("edit.paste", params)?;
let id = layer_param(s, &Value::Null)?;
s.execute("layer.layerMask.revealAll", json!({"layer": id.0, "coalesce": key}))?;
@@ -413,9 +387,9 @@ fn paste_into(s: &mut Session, p: &Value, outside: bool) -> Result<Value> {
Ok(())
});
s.coalesce_request = None;
// Three revisions: `Session::dispatch` reports what the whole command changed, so only where
// the masked paste draws is recomposited (#2901).
r2?;
// Only where the masked paste draws needs recompositing (#2901).
crate::layer_multi_cmds::note_insert(s, &before);
Ok(r)
}
@@ -1119,7 +1093,6 @@ pub fn specs() -> Vec<CommandSpec> {
has_layer,
show_only
),
spec!("filter.blur.average", "Average", &["Filter", "Blur"], None, "{}", has_pixels, average),
]
}
+63 -1
View File
@@ -24,7 +24,7 @@ fn equalize_average_and_clouds_edit_the_targeted_channel() {
s.tools.foreground = [0.0, 0.0, 0.0, 1.0];
s.tools.background = [1.0, 1.0, 1.0, 1.0];
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
let p = match target {
let mut p = match target {
"quickMask" => {
s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap();
json!({"seed": 1})
@@ -39,6 +39,10 @@ fn equalize_average_and_clouds_edit_the_targeted_channel() {
json!({"seed": 1, "target": "mask"})
}
};
// Average has no seed parameter; only Clouds uses it.
if cmd == "filter.blur.average" {
p.as_object_mut().unwrap().remove("seed");
}
// Two levels in the target, so Equalize and Average have something to change.
let edit_target = json!({ "target": if target == "alpha" { json!({"channel": 0}) } else { json!(target) } });
s.edit("levels", |doc, active| {
@@ -65,6 +69,18 @@ fn equalize_average_and_clouds_edit_the_targeted_channel() {
let case = format!("{cmd} on {target} at {depth}");
assert_eq!(layer1, layer0, "{case}: the layer is untouched");
assert_ne!(target1, target0, "{case}: the target changed");
if cmd == "filter.blur.average" {
// The equal-sized halves contribute equally, using their stored sample values.
let mean = (f64::from(target0[0]) + f64::from(target0[20])) / 2.0;
let tolerance = match depth {
8 => 1.0 / 255.0,
16 => 1.0 / 65535.0,
_ => 1e-6,
};
for value in &target1 {
assert!((f64::from(*value) - mean).abs() <= tolerance, "{case}: {value}, expected {mean}");
}
}
assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{case}");
s.undo();
assert_eq!(read(&s).1, target0, "{case}: undo restores the target");
@@ -556,6 +572,52 @@ fn clouds_in_a_selection_are_the_canvas_clouds() {
}
}
#[test]
fn average_preserves_transparency_and_averages_hidden_colours() {
// Photoshop 26.6.1, RGB8 PNG with opaque red and transparent blue halves:
// Average produces (128, 0, 128), retaining each pixel's original alpha.
for depth in [8, 16, 32] {
let mut s = session(depth);
paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 1.0]);
paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 0.0]);
let bounds = Rect::new(0, 0, 40, 30);
let before = active(&s).surface().unwrap().read_region(bounds);
let steps = s.active().unwrap().history.past_len();
s.execute("filter.blur.average", json!({})).unwrap();
let after = active(&s).surface().unwrap().read_region(bounds);
for (old, new) in before.as_chunks::<4>().0.iter().zip(after.as_chunks::<4>().0) {
assert_eq!(new[3], old[3], "depth {depth}: Average must preserve alpha");
assert!((new[0] - 0.5).abs() < 0.003 && new[1] == 0.0 && (new[2] - 0.5).abs() < 0.003, "{depth}: {new:?}");
}
assert_eq!(s.active().unwrap().history.past_len(), steps + 1);
s.undo();
assert_eq!(active(&s).surface().unwrap().read_region(bounds), before);
s.redo();
assert_eq!(active(&s).surface().unwrap().read_region(bounds), after);
}
}
#[test]
fn average_preserves_partial_alpha_and_pixels_outside_selection() {
for depth in [8, 16, 32] {
let mut s = session(depth);
paint_square(&mut s, Rect::new(0, 0, 20, 30), [1.0, 0.0, 0.0, 0.25]);
paint_square(&mut s, Rect::new(20, 0, 40, 30), [0.0, 0.0, 1.0, 0.75]);
s.execute("select.rect", json!({"x": 10, "y": 0, "width": 15, "height": 30})).unwrap();
let before: Vec<_> = (0..40).map(|x| pixel(&s, x, 15)).collect();
s.execute("filter.blur.average", json!({})).unwrap();
for x in 0..40 {
let p = pixel(&s, x, 15);
assert_eq!(p[3], before[x as usize][3], "depth {depth}, x {x}");
if (10..25).contains(&x) {
assert!((p[0] - 2.0 / 3.0).abs() < 0.003 && (p[2] - 1.0 / 3.0).abs() < 0.003, "{depth}: {p:?}");
} else {
assert_eq!(p, before[x as usize]);
}
}
}
}
#[test]
fn average_and_clouds() {
let mut s = session(8);
+16
View File
@@ -24,6 +24,7 @@ mod batch_run;
mod export;
mod info;
mod open;
mod open_as_smart_object;
mod paths;
mod place_steps;
mod processing;
@@ -50,6 +51,8 @@ pub(crate) use open::{BatchOpen, batch_open_notice, batch_open_params, remember_
pub use open::{PLACE_EMBEDDED, open_bytes_as, open_bytes_as_with_options, place_bytes, raw_defaults};
pub(crate) use open::{PlaceInput, apply_place, import, import_with_options, tag_exr_colorspace};
use open::{approve_memory, close_all, close_others, open_as, place, revert};
pub use open_as_smart_object::admit_as_smart_object;
use open_as_smart_object::open_as_smart_object;
use paths::is_file;
#[cfg(test)]
use paths::openable_name;
@@ -285,6 +288,15 @@ pub fn specs() -> Vec<CommandSpec> {
native,
open_as
),
spec!(
"file.openAsSmartObject",
"Open as Smart Object…",
&["File"],
None,
r##"{"path":str,"confirmDamage":bool=false (a damaged PSD waits for an answer, as File > Open's does)} (opens the file as a new untitled document named "<file name without its last extension>-N" with the file's size, resolution, colour mode, bit depth and profile, holding one embedded smart object layer named after the file) → {document, docId, name, layer, warnings, color, smartObject} (or {held, name, warnings, color, damaged, smartObject} while a prompt waits)"##,
native,
open_as_smart_object
),
// One-shot permission for one file, not something to replay later: never journaled or
// recorded in an action, since replaying it in another session/on another file would
// grant memory use nobody approved (#10897). It also releases the queued source on both
@@ -421,6 +433,10 @@ mod tests;
#[path = "file_cmds/place_job_tests.rs"]
mod place_job_tests;
#[cfg(test)]
#[path = "file_cmds/open_as_smart_object_tests.rs"]
mod open_as_smart_object_tests;
#[cfg(test)]
mod aces_exr_tests {
use super::*;
+9 -3
View File
@@ -74,9 +74,15 @@ fn import_result(name: &str, bytes: &[u8]) -> Result<photocraft_io::ImportResult
/// The one import path every caller shares: allocation checkpoint, native `.pcraft` and format
/// dispatch through `photocraft_io::import_with_options`, typed memory refusals, and the
/// preview-only refusal wherever the import came from.
fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<photocraft_io::ImportResult> {
pub(super) fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<photocraft_io::ImportResult> {
import_result_for_open(name, bytes, opts).map(|(r, _)| r)
}
/// [`import_result_with`], also telling whether a PSD/PSB had damaged data it recovered from, as
/// File › Open's job learns it (`photocraft_io::import_for_open`), so an interactive caller can ask.
pub(super) fn import_result_for_open(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result<(photocraft_io::ImportResult, bool)> {
crate::allocation::checkpoint("importing document")?;
let r = photocraft_io::import_with_options(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?;
let (r, damaged) = photocraft_io::import_for_open(name, bytes, opts).map_err(|e| crate::error::io_open_error(name, e))?;
// Auxiliary imports return only a document and cannot surface the preview's fidelity warning.
// Open has its own warning-preserving path; never silently place or process a thumbnail.
if r.preview_only {
@@ -84,7 +90,7 @@ fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOpti
"{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here"
)));
}
Ok(r)
Ok((r, damaged))
}
// ---------- close / revert / save a copy / open as ----------
@@ -0,0 +1,115 @@
//! File › Open as Smart Object… (#11678): a file opens as a new untitled document with the file's
//! size, resolution, colour mode, bit depth and profile, holding one embedded smart object layer.
//!
//! The layer is built as File › Place Embedded builds one (an embedded smart object at the file's own
//! size and position `0, 0`) and put into the document before it is admitted, so the opening
//! snapshot already shows it.
use super::open::import_result_for_open;
use super::paths::{file_name, read_file, stem, untitled_name};
use super::{Affine, Arc, Document, Layer, LayerContent, Result, Session, SmartObject, SmartSource, Value, flattened_checked, json, str_param};
use crate::layer_place::Place;
const CMD: &str = "file.openAsSmartObject";
/// The history step's name.
const LABEL: &str = "Open As Smart Object";
/// Opens the file as a document holding one embedded smart object. The read, decode and flatten
/// run on the job's worker (inline under `execute`); the document is built, given File › Open's
/// colour policy and admitted, or held for its profile prompt, when the job is applied. The reply
/// has the shape of File › Open's job: `{document, docId, name, layer, warnings, color}`, or
/// `{held, name, warnings, color, smartObject}` while the profile prompt waits.
pub(super) fn open_as_smart_object(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path", CMD)?.to_string();
let name = file_name(&path);
let opts = crate::jobs::import_options(s.prefs());
// An interactive caller (the app) asks before opening a PSD that had damaged data, as File > Open does.
let confirm_damage = p.get("confirmDamage").and_then(Value::as_bool).unwrap_or(false);
crate::jobs::run(
s,
&format!("Opening {name}"),
false,
move |ctx| {
ctx.progress(0.0, "Reading");
let bytes = read_file(&path)?;
ctx.check()?;
ctx.progress(0.05, "Decoding");
let (r, damaged) = import_result_for_open(&name, &bytes, &opts)?;
ctx.check()?;
ctx.progress(0.9, "Flattening");
// The file as one image: the smart object's rendered contents.
let pixels = flattened_checked(&r.document, r.document.pixel_format(), CMD)?;
Ok((path, name, Arc::new(bytes), r, pixels, confirm_damage && damaged))
},
|s, (path, name, bytes, r, pixels, damaged)| apply(s, &path, &name, bytes, r, pixels, damaged),
)
}
fn apply(
s: &mut Session,
path: &str,
file: &str,
bytes: Arc<Vec<u8>>,
r: photocraft_io::ImportResult,
pixels: photocraft_raster::Surface,
damaged: bool,
) -> Result<Value> {
let warnings = r.warnings;
let mut src = r.document;
super::tag_exr_colorspace(s, file, &mut src);
super::raw_defaults(s, &warnings, &mut src);
let layer_name = stem(path);
// "<name>-1", the next free number while a document with that name is open.
let name = untitled_name(&layer_name, |n| s.documents().iter().any(|d| d.doc.name == n) || s.held_open_named(n));
let mut doc = Document::new(name.clone(), src.size, src.mode, src.depth);
doc.resolution_dpi = src.resolution_dpi;
doc.icc_profile = src.icc_profile.clone();
doc.color_table = src.color_table.clone();
doc.duotone = src.duotone.clone();
// Embedded (not linked): the original file name keeps its extension, so Edit Contents opens it.
let source = SmartSource::Embedded { file_name: file.to_string(), bytes };
let so = SmartObject::new(source, Affine { m: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0] }, Some(pixels));
let layer = Layer::new(layer_name, LayerContent::Smart(so));
let layer_id = layer.id;
crate::layer_place::insert_new(&mut doc, None, layer, Place::AutoEditable);
// File › Open's completion: a raw has no embedded profile to ask about; otherwise the profile
// prompt holds the document, and without a question the Color Settings policy is applied.
let raw = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE));
let question = s.color.open_question(&doc).filter(|_| !raw);
if damaged || question.is_some() {
let held = s.hold_open(doc, false);
return Ok(json!({"held": held, "name": name, "warnings": warnings, "color": question, "damaged": damaged, "smartObject": true}));
}
let color = s.color.open_policy(&mut doc, s.prefs().file_handling.ignore_exif_profile_tag);
let index = admit_as_smart_object(s, doc);
let id = s.documents().get(index).map(|st| st.doc.id.0);
// Admission numbers the document again, so the reply reads the name it was admitted under.
let name = s.documents().get(index).map_or(name, |st| st.doc.name.clone());
Ok(json!({"document": index, "docId": id, "name": name, "layer": layer_id.0, "warnings": warnings, "color": color, "smartObject": true}))
}
/// Admits a document built by Open as Smart Object (one smart object layer) as an untitled
/// document: the opening snapshot already shows the placed layer, is named after it, and the
/// history is the single state "Open As Smart Object", as File › Open's is one state.
pub fn admit_as_smart_object(s: &mut Session, mut doc: Document) -> usize {
let layer_name = doc.layers.first().map(|l| l.name.clone());
// The number was free when the file was read, but documents held for their prompts did not count
// then, and one of them may have been cancelled since: take the first free one now, as each
// document is admitted.
if let Some(base) = &layer_name {
doc.name = untitled_name(base, |n| s.documents().iter().any(|d| d.doc.name == n));
}
// Untitled: no path, so Save asks where to save.
let index = s.add_document(doc, None);
if let Some(st) = s.active_mut() {
if let (Some(first), Some(name)) = (st.snapshots.iter_mut().find(|snap| snap.id == 0), layer_name) {
first.name = name;
}
st.history.set_current_label(LABEL);
}
index
}
@@ -0,0 +1,367 @@
//! File › Open as Smart Object… (#11678): a file opens as a new untitled document holding one
//! embedded smart object layer.
use super::*;
fn tmp(name: &str) -> String {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let d = std::env::temp_dir().join(format!("photocraft-open-as-so-{}-{name}-{id}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d.to_string_lossy().into_owned()
}
/// A small PNG with a gradient, so the pixels differ from place to place.
fn write_png(dir: &str, name: &str, w: u32, h: u32) -> String {
let px: Vec<u8> = (0..h).flat_map(|y| (0..w).flat_map(move |x| [(x * 255 / w) as u8, (y * 255 / h) as u8, ((x + y) % 256) as u8])).collect();
let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, px).unwrap();
let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();
let path = join(dir, name);
std::fs::write(&path, bytes).unwrap();
path
}
/// A two-layer 16-bit PSD at 300 ppi tagged with Display P3, made with the engine's own save.
fn write_psd16(dir: &str, name: &str, w: u32, h: u32) -> String {
let mut s = Session::new();
s.execute("file.new", json!({"width": w, "height": h, "depth": 16})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("image.imageSize", json!({"resolution": 300, "resample": "none"})).unwrap();
s.execute("edit.assignProfile", json!({"profile": "display-p3"})).unwrap();
let path = join(dir, name);
save_doc(&s.active().unwrap().doc, &path, None).unwrap();
path
}
fn imported(path: &str) -> Document {
photocraft_io::import(&file_name(path), &std::fs::read(path).unwrap()).unwrap().document
}
fn active(s: &Session) -> &Document {
&s.active().unwrap().doc
}
fn names(s: &Session) -> Vec<String> {
s.documents().iter().map(|d| d.doc.name.clone()).collect()
}
/// The one layer of the active document, which must be an embedded smart object.
fn embedded(s: &Session) -> (String, String, Arc<Vec<u8>>) {
let d = active(s);
assert_eq!(d.layers.len(), 1, "one layer, not a Background plus a layer");
let layer = &d.layers[0];
match &layer.content {
LayerContent::Smart(so) => match &so.source {
SmartSource::Embedded { file_name, bytes } => (layer.name.clone(), file_name.clone(), Arc::clone(bytes)),
other => panic!("expected an embedded smart object, got {other:?}"),
},
_ => panic!("the layer is not a smart object"),
}
}
#[test]
fn a_png_opens_as_an_untitled_document_with_one_embedded_smart_object() {
let dir = tmp("png");
let path = write_png(&dir, "a_test.png", 64, 48);
let mut s = Session::new();
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(r["name"], "a_test-1", "{r}");
assert_eq!(s.documents().len(), 1);
let st = s.active().unwrap();
assert_eq!(st.doc.name, "a_test-1");
assert_eq!(st.path, None, "untitled: Save asks where to save");
let file = imported(&path);
let d = &st.doc;
assert_eq!((d.size.width, d.size.height), (64, 48));
assert_eq!(d.resolution_dpi, file.resolution_dpi);
assert_eq!((d.mode, d.depth), (file.mode, file.depth));
assert_eq!(d.icc_profile, file.icc_profile);
let (layer, original, bytes) = embedded(&s);
assert_eq!(layer, "a_test", "named after the file without its extension");
assert_eq!(original, "a_test.png", "Edit Contents opens the original file name");
assert_eq!(*bytes, std::fs::read(&path).unwrap(), "the file itself is embedded");
}
#[test]
fn the_smart_object_shows_the_file() {
let dir = tmp("pixels");
let path = write_png(&dir, "grad.png", 32, 16);
let mut s = Session::new();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let want = photocraft_compose::render(&imported(&path), Rect::new(0, 0, 32, 16)).px.clone();
let got = photocraft_compose::render(active(&s), Rect::new(0, 0, 32, 16)).px.clone();
assert_eq!(got, want);
}
#[test]
fn a_16_bit_psd_keeps_size_resolution_mode_depth_and_profile() {
let dir = tmp("psd");
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
let mut s = Session::new();
// The files were measured in the working spaces, where nothing asks; Preserve keeps Display P3.
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let file = imported(&path);
assert_eq!(file.resolution_dpi, 300.0);
assert!(file.icc_profile.is_some());
let d = active(&s);
assert_eq!(d.name, "c.layered-1", "only the last extension is dropped");
assert_eq!((d.size.width, d.size.height), (40, 30));
assert_eq!(d.resolution_dpi, 300.0);
assert_eq!((d.mode, d.depth), (file.mode, file.depth));
assert_eq!(d.depth, photocraft_doc::SampleType::U16);
assert_eq!(d.icc_profile, file.icc_profile);
let (layer, original, _) = embedded(&s);
assert_eq!((layer.as_str(), original.as_str()), ("c.layered", "c.layered.psd"));
}
#[test]
fn history_is_the_single_state_open_as_smart_object() {
let dir = tmp("history");
let path = write_png(&dir, "a_test.png", 16, 16);
let mut s = Session::new();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let st = s.active().unwrap();
assert_eq!(st.history.entries(), ["Open As Smart Object"], "one state, as File > Open has");
assert_eq!(st.snapshots.first().map(|snap| snap.name.as_str()), Some("a_test"), "the opening snapshot is named after the layer");
}
#[test]
fn the_opening_snapshot_shows_the_placed_smart_object() {
let dir = tmp("snapshot");
let path = write_png(&dir, "a_test.png", 16, 16);
let mut s = Session::new();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let st = s.active().unwrap();
let first = st.snapshots.first().unwrap();
assert_eq!(first.doc.layers.len(), 1, "snapshot 0 already holds the smart object");
assert!(matches!(first.doc.layers[0].content, LayerContent::Smart(_)));
assert_eq!(first.layers.active, Some(first.doc.layers[0].id));
assert_eq!(st.active_layer, Some(first.doc.layers[0].id));
assert_eq!(st.history.entries(), ["Open As Smart Object"]);
}
#[test]
fn the_number_is_the_next_free_one_and_starts_again_after_they_close() {
let dir = tmp("numbers");
let path = write_png(&dir, "a_test.png", 8, 8);
let mut s = Session::new();
for _ in 0..3 {
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
}
assert_eq!(names(&s), ["a_test-1", "a_test-2", "a_test-3"]);
while !s.documents().is_empty() {
s.close(0);
}
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(names(&s), ["a_test-1"]);
}
#[test]
fn a_plain_open_of_the_same_file_is_unchanged() {
let dir = tmp("plain");
let path = write_png(&dir, "a_test.png", 8, 8);
let mut s = Session::new();
s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
open_bytes_as(&mut s, &path, &std::fs::read(&path).unwrap(), None, Some(path.clone())).unwrap();
assert_eq!(names(&s), ["a_test-1", "a_test.png"]);
assert!(matches!(active(&s).layers[0].content, LayerContent::Raster(_)));
}
#[test]
fn several_files_open_one_document_each() {
let dir = tmp("several");
let a = write_png(&dir, "a_test.png", 8, 8);
let b = write_psd16(&dir, "d_other.psd", 12, 10);
let mut s = Session::new();
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
s.execute("file.openAsSmartObject", json!({"path": a})).unwrap();
s.execute("file.openAsSmartObject", json!({"path": b})).unwrap();
assert_eq!(names(&s), ["a_test-1", "d_other-1"]);
for st in s.documents() {
assert_eq!(st.doc.layers.len(), 1);
assert!(matches!(st.doc.layers[0].content, LayerContent::Smart(_)));
}
}
#[test]
fn a_missing_or_unreadable_file_is_an_error_not_a_crash() {
let dir = tmp("bad");
let junk = join(&dir, "notes.png");
std::fs::write(&junk, b"this is not an image").unwrap();
let text = join(&dir, "readme.txt");
std::fs::write(&text, b"hello").unwrap();
let mut s = Session::new();
for path in [join(&dir, "missing.png"), junk, text] {
let r = s.execute("file.openAsSmartObject", json!({"path": path}));
assert!(r.is_err(), "{path}: {r:?}");
}
assert!(s.documents().is_empty(), "a failed open leaves no document behind");
}
#[test]
fn bad_params_are_errors() {
let mut s = Session::new();
for params in [json!({}), json!({"path": 7}), json!({"path": null})] {
let r = s.execute("file.openAsSmartObject", params.clone());
assert!(r.is_err(), "{params}: {r:?}");
}
assert!(s.documents().is_empty());
}
fn job(r: crate::jobs::Started) -> crate::jobs::JobId {
match r {
crate::jobs::Started::Job(id) => id,
crate::jobs::Started::Done(v) => panic!("expected a background job, ran inline: {v}"),
}
}
/// Poll until job `id` ends (or 60 s pass); returns its event.
fn wait_event(s: &mut Session, id: crate::jobs::JobId) -> crate::jobs::JobEvent {
let t = std::time::Instant::now();
loop {
if let Some(e) = s.poll_jobs().into_iter().find(|e| e.id == id) {
return e;
}
assert!(t.elapsed() < std::time::Duration::from_secs(60), "job {id:?} did not finish");
std::thread::sleep(std::time::Duration::from_millis(2));
}
}
#[test]
fn the_import_runs_as_a_job_when_started() {
let dir = tmp("job");
let path = write_png(&dir, "a_test.png", 32, 24);
let mut s = Session::new();
let id = job(s.start("file.openAsSmartObject", json!({"path": path})).unwrap());
assert!(s.documents().is_empty(), "nothing is admitted before the job is applied");
let e = wait_event(&mut s, id);
let crate::jobs::JobOutcome::Done(v) = &e.outcome else { panic!("{e:?}") };
assert!(v["docId"].is_u64(), "{v}");
assert_eq!(v["name"], "a_test-1", "{v}");
assert_eq!(s.documents().len(), 1);
embedded(&s);
}
#[test]
fn the_colour_policy_matches_file_open() {
let dir = tmp("policy");
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
let settings = json!({"askOnMismatch": false, "policyRgb": "convert"});
let mut open = Session::new();
open.execute("edit.colorSettings", settings.clone()).unwrap();
open.execute("file.openAs", json!({"path": path})).unwrap();
let mut so = Session::new();
so.execute("edit.colorSettings", settings).unwrap();
so.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let (a, b) = (active(&open), active(&so));
assert_eq!(a.icc_profile, b.icc_profile, "Convert is applied as File > Open applies it");
assert_eq!((a.mode, a.depth, a.size), (b.mode, b.depth, b.size));
assert_eq!(a.resolution_dpi, b.resolution_dpi);
}
#[test]
fn ask_when_opening_holds_the_document_like_file_open() {
let dir = tmp("ask");
let path = write_psd16(&dir, "c.layered.psd", 40, 30);
let mut s = Session::new();
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(r["color"]["ask"], true, "{r}");
assert_eq!(r["smartObject"], true, "{r}");
assert!(r["held"].is_u64(), "{r}");
assert!(s.documents().is_empty(), "held for the profile prompt, not admitted");
let (doc, _) = s.take_held_open(r["held"].as_u64().unwrap()).unwrap();
assert_eq!(doc.name, "c.layered-1");
assert_eq!(doc.layers.len(), 1);
assert!(matches!(doc.layers[0].content, LayerContent::Smart(_)));
}
#[test]
fn the_reply_flags_a_smart_object_so_a_queued_document_keeps_its_history_label() {
let dir = tmp("flag");
let path = write_png(&dir, "a_test.png", 16, 12);
let mut s = Session::new();
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(r["smartObject"], true, "{r}");
}
#[test]
fn a_damaged_psd_is_held_for_confirmation_when_asked_and_opens_otherwise() {
let dir = tmp("damaged");
let path = join(&dir, "d.psd");
std::fs::write(&path, crate::jobs::psd_open_fixture::make_psd(true)).unwrap();
let mut s = Session::new();
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
let r = s.execute("file.openAsSmartObject", json!({"path": path, "confirmDamage": true})).unwrap();
assert_eq!(r["damaged"], true, "{r}");
assert_eq!(r["smartObject"], true, "{r}");
assert!(r["held"].is_u64(), "{r}");
assert!(s.documents().is_empty(), "held for the damage prompt, not admitted");
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert!(r["docId"].is_u64(), "a headless caller opens the recovered content: {r}");
}
#[test]
fn a_document_held_for_its_prompt_does_not_share_its_name_with_the_next() {
let dir = tmp("held-name");
let path = write_psd16(&dir, "a_test.psd", 20, 20);
let mut s = Session::new();
let first = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let second = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(first["name"], "a_test-1");
assert_eq!(second["name"], "a_test-2", "the held document's name is taken: {second}");
// Both held docs leave the session for the app's queue; admitting them one by one numbers each.
let (a, _) = s.take_held_open(first["held"].as_u64().unwrap()).unwrap();
let (b, _) = s.take_held_open(second["held"].as_u64().unwrap()).unwrap();
admit_as_smart_object(&mut s, a);
admit_as_smart_object(&mut s, b);
assert_eq!(names(&s), ["a_test-1", "a_test-2"]);
let mut t = Session::new();
let (c, _) = {
let r = t.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
t.take_held_open(r["held"].as_u64().unwrap()).unwrap()
};
let (d, _) = {
t.execute("edit.colorSettings", json!({"askOnMismatch": true})).unwrap();
let r = t.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
t.take_held_open(r["held"].as_u64().unwrap()).unwrap()
};
assert_eq!(c.name, d.name, "taken out of the session, both are named a_test-1 when read");
admit_as_smart_object(&mut t, c);
admit_as_smart_object(&mut t, d);
assert_eq!(names(&t), ["a_test-1", "a_test-2"], "the second takes the next free number when admitted");
}
#[test]
fn a_cancelled_hold_frees_its_number_for_the_one_admitted_after_it() {
let dir = tmp("cancelled-hold");
let path = write_psd16(&dir, "photo.psd", 20, 20);
let mut s = Session::new();
let first = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
let second = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!((first["name"].as_str(), second["name"].as_str()), (Some("photo-1"), Some("photo-2")));
// photo-1 is cancelled while photo-2 waits; photo-2 is admitted with nothing open.
s.take_held_open(first["held"].as_u64().unwrap()).unwrap();
let (b, _) = s.take_held_open(second["held"].as_u64().unwrap()).unwrap();
admit_as_smart_object(&mut s, b);
assert_eq!(names(&s), ["photo-1"], "the first free number is taken at admission, with no collision");
}
#[test]
fn the_reply_names_the_document_as_admitted() {
let dir = tmp("reply-name");
let path = write_psd16(&dir, "photo.psd", 20, 20);
let mut s = Session::new();
s.execute("edit.colorSettings", json!({"askOnMismatch": true})).unwrap();
let held = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(held["name"], "photo-1", "{held}");
assert!(held["held"].is_u64(), "{held}");
// The next open skips the prompt: photo-1 is held, so the number read was 2, but admission takes the first free one.
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
let r = s.execute("file.openAsSmartObject", json!({"path": path})).unwrap();
assert_eq!(names(&s), ["photo-1"], "{r}");
assert_eq!(r["name"], "photo-1", "the reply carries the name the document was admitted under: {r}");
}
+10 -3
View File
@@ -5,9 +5,12 @@ use photocraft_io::{ImportResult, raw::RawTuning};
use super::{EngineError, Result, Session, Value, json};
/// The prior settings of a sidecar, and its crop (in the raw's stored orientation).
type Prior = (CameraRaw, Option<photocraft_io::camera_raw_xmp::Crop>);
/// Read only a bounded regular XMP file. No ambient sidecar reads are granted to gated sessions.
#[cfg(not(target_arch = "wasm32"))]
fn prior_settings(path: Option<&str>) -> Result<Option<CameraRaw>> {
fn prior_settings(path: Option<&str>) -> Result<Option<Prior>> {
use std::io::Read;
let Some(path) = path else { return Ok(None) };
let sidecar = match path.rsplit_once('.') {
@@ -31,11 +34,11 @@ fn prior_settings(path: Option<&str>) -> Result<Option<CameraRaw>> {
if !report.ignored.is_empty() {
return Err(EngineError::Other(format!("{sidecar}: unsupported prior RAW settings: {}", report.ignored.join(", "))));
}
Ok(Some(settings))
Ok(Some((settings, report.crop)))
}
#[cfg(target_arch = "wasm32")]
fn prior_settings(path: Option<&str>) -> Result<Option<CameraRaw>> {
fn prior_settings(path: Option<&str>) -> Result<Option<Prior>> {
if path.is_some() { Err(EngineError::Other("cannot read RAW sidecars on the web".into())) } else { Ok(None) }
}
@@ -67,6 +70,8 @@ pub(super) fn prepare(s: &Session, name: &str, path: Option<&str>, bytes: &[u8])
return Err(EngineError::Other("RAW sidecar opening requires a trusted session; no implicit read capability is available".into()));
}
let prior = prior_settings(path)?;
let crop = prior.as_ref().and_then(|(_, crop)| *crop);
let prior = prior.map(|(settings, _)| settings);
let mut settings = prior.clone().unwrap_or_default();
let opts = crate::jobs::import_options(s.prefs());
let mut imported = photocraft_io::import_with_options(name, bytes, &opts).map_err(|error| EngineError::Other(format!("{name}: {error}")))?;
@@ -87,6 +92,8 @@ pub(super) fn prepare(s: &Session, name: &str, path: Option<&str>, bytes: &[u8])
clarity: settings.clarity,
texture: settings.texture,
dehaze: settings.dehaze,
// The sidecar's crop, as the interactive open applies it: before the Camera Raw step.
crop,
};
if tuning != (RawTuning { demosaic: opts.demosaic, ..Default::default() }) {
super::open::raw_defaults(s, &imported.warnings, &mut imported.document);
+21
View File
@@ -734,6 +734,27 @@ fn batch_quiet_raw_applies_prior_settings_and_workflow_without_touching_inputs()
assert!(s.batch_open_notices.is_none());
}
/// #9985: quiet RAW opening crops to the sidecar's crop, as the interactive open does.
#[test]
fn batch_quiet_raw_applies_the_sidecar_crop() {
use photocraft_raw::testgen::{DngSpec, mosaic, scene};
let dir = tmp("batch-quiet-raw-crop");
let path = join(&dir, "raw.dng");
let (w, h) = (24, 16);
let bytes = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 65535)).build();
std::fs::write(&path, &bytes).unwrap();
let crop = photocraft_io::camera_raw_xmp::Crop { top: 0.25, left: 0.125, bottom: 0.75, right: 0.625 };
let xmp = photocraft_io::camera_raw_xmp::save_with_crop(&photocraft_algo::camera_raw::CameraRaw::default(), Some(crop));
std::fs::write(join(&dir, "raw.xmp"), &xmp).unwrap();
let mut s = Session::new();
let output = join(&dir, "out");
let p = json!({"input":[path],"output":output,"format":"psd","suppressOpenOptions":true,"suppressWarnings":true,"steps":[]});
let result = s.execute("file.automate.batch", p).unwrap();
assert!(result["errors"].as_array().unwrap().is_empty(), "{result}");
let actual = photocraft_io::import("raw.psd", &std::fs::read(join(&output, "raw.psd")).unwrap()).unwrap().document;
assert_eq!((actual.size.width, actual.size.height), (12, 8), "the 24x16 frame cropped to x 3..15, y 4..12");
}
fn tmp(name: &str) -> String {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+1 -1
View File
@@ -1256,7 +1256,7 @@ pub fn specs() -> Vec<CommandSpec> {
"image.mode.rgb",
"RGB Color",
["Image", "Mode"],
r##"{"profile":"<builtin id>|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##,
r##"{"profile":"<builtin id>|working|/path/to/profile.icc"=working (Indexed→RGB preserves the document profile unless explicit),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##,
has_doc,
|s, p| convert_mode(s, ColorMode::Rgb, p)
),
+376
View File
@@ -0,0 +1,376 @@
//! Layer › Copy CSS (#9372): CSS for the selected layers, in the form Photoshop writes. The
//! command returns the text; the shell puts it on the clipboard.
//!
//! Each layer is a class named after it (punctuation and spaces become `_`, and a leading digit
//! gets a `_` in front). What is written, in this order:
//! - a type layer: `font-size`, `font-family`, `color`, `line-height` and `text-align`, from its
//! first run and first paragraph;
//! - a live rounded rectangle: `border-radius`; a live ellipse: `border-radius: 50%`;
//! - a shape or fill layer with a solid colour: `background-color`; any other layer (pixels,
//! gradient or pattern fills, smart objects): `background-image`, an image named after it;
//! - `opacity` when it isn't 100 %;
//! - `position: absolute`, `left` and `top`, and `width` and `height` except for point type;
//! - `z-index`, its place in the stack counted from the bottom layer as 1, where a group takes
//! two places (its own, and one below its layers for the group's end).
//!
//! A group writes only its box (the canvas, or its artboard) and z-index, followed by the rule
//! of every layer in it, top first. A fill layer without a vector mask and an adjustment layer
//! have no rule, and Copy CSS is off when no selected layer has one. Point type is placed as
//! Photoshop places it (see [`place_point_text`]).
//!
//! Not written: strokes (`border`), layer effects (`box-shadow`, `text-shadow`), gradients as
//! CSS gradients, blend modes (`mix-blend-mode`), fill opacity, the styles of later runs and
//! paragraphs, the corners of a rounded rectangle scaled unequally (elliptical, while it keeps
//! one radius per corner), and the geometry of other shapes (live polygons, stars and lines, and
//! custom paths), which get the rule of their box.
use std::collections::HashMap;
use std::sync::PoisonError;
use photocraft_doc::text::{Orientation, TextAlign, TextShape};
use photocraft_doc::{Document, Fill, Layer, LayerContent, LayerId, LiveShape, Path, TextLayer};
use photocraft_geom::{Point, Rect};
use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::{EngineError, Result, Session};
pub const ID: &str = "layer.copyCSS";
fn bad(message: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: ID.into(), msg: message.into() }
}
/// Deepest group nesting followed; deeper layers are left out rather than recursing without end.
const MAX_DEPTH: usize = 256;
fn enabled(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
let ids = st.selected_layers();
if ids.is_empty() {
return Err("no layer selected".into());
}
// Photoshop greys Copy CSS out for a fill layer without a shape (measured), and for an
// adjustment layer, which has nothing to place either.
if st.doc.walk().iter().any(|(_, _, l)| ids.contains(&l.id) && has_css(l)) { Ok(()) } else { Err("no selected layer has CSS".into()) }
}
/// Whether a layer can have a rule (one with nothing to place still gets none).
fn has_css(l: &Layer) -> bool {
match &l.content {
LayerContent::Adjustment(_) => false,
LayerContent::Fill(_) => l.vector_mask.is_some(),
_ => true,
}
}
/// A number as Photoshop writes it in CSS: at most three decimals, no trailing zeros.
pub fn number(v: f64) -> String {
let v = if v.is_finite() { (v * 1000.0).round() / 1000.0 } else { 0.0 };
decimals(v)
}
/// A `left` or `top` as Photoshop writes it: cut after three decimals, not rounded (measured:
/// 49.8125 is `49.812px`, 176.5668 is `176.566px`). The nudge keeps 127.1, computed as
/// 127.0999…, at `127.1`.
pub fn position(v: f64) -> String {
let v = if v.is_finite() { (v * 1000.0 + 1e-6).floor() / 1000.0 } else { 0.0 };
decimals(v)
}
fn decimals(v: f64) -> String {
let s = format!("{v:.3}");
let s = s.trim_end_matches('0').trim_end_matches('.');
if s == "-0" { "0".into() } else { s.to_string() }
}
/// The class name for a layer: its name with every character other than a letter, digit or `_`
/// as `_` (a hyphen too, as Photoshop does), and a `_` in front when it starts with a digit,
/// which a class selector can't.
pub fn class_name(name: &str) -> String {
let s: String = name.chars().map(|c| if c.is_alphanumeric() || c == '_' { c } else { '_' }).collect();
if s.is_empty() {
"layer".into()
} else if s.starts_with(|c: char| c.is_ascii_digit()) {
format!("_{s}")
} else {
s
}
}
/// `s` as a double-quoted CSS string, escaped as CSSOM serializes one: `"` and `\` get a
/// backslash, control characters (line breaks among them) become hex escapes, NUL becomes U+FFFD.
pub fn quoted(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'\0' => out.push('\u{FFFD}'),
'\u{1}'..='\u{1F}' | '\u{7F}' => out.push_str(&format!("\\{:x} ", u32::from(c))),
'"' | '\\' => {
out.push('\\');
out.push(c);
}
_ => out.push(c),
}
}
out.push('"');
out
}
/// The image Photoshop names after a layer, as a `url()`.
fn image(l: &Layer) -> String {
format!("url({})", quoted(&format!("{}.png", l.name)))
}
fn rgb(c: &photocraft_color::Color) -> String {
let [r, g, b] = c.to_rgb().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
format!("rgb({r}, {g}, {b})")
}
/// Whether `path` is the outline `live` draws: every anchor of one is an anchor of the other,
/// within a hundredth of a pixel, in any order or direction (a flipped shape runs the other way).
/// A live rectangle scaled unequally keeps one radius per corner, but its path keeps the corners
/// it was drawn with, now elliptical, so the two differ.
fn draws(live: &LiveShape, path: &Path) -> bool {
let anchors = |p: &Path| p.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| k.anchor)).collect::<Vec<_>>();
let (have, want) = (anchors(path), anchors(&photocraft_vector::shapes::live_path(live)));
let among = |p: &Point, q: &[Point]| q.iter().any(|q| (p.x - q.x).abs() < 0.01 && (p.y - q.y).abs() < 0.01);
have.iter().all(|p| among(p, &want)) && want.iter().all(|p| among(p, &have))
}
/// Where Photoshop places point type, from its pixel bounds `pix`, its ink `ink` (`[x0, y0, x1,
/// y1]` from its origin, unrounded), its first baseline `baseline` in the same space, the cap
/// height `cap` of its font and its size and line height in px. Measured on Arial and Times New
/// Roman at 24 and 48 px, with auto and explicit leading:
/// - `left` is the pixel left less the ink's offset from the origin ("Hello": 52 − 1.875 =
/// `50.125`);
/// - without a descender, the line box is centred on the pixels ("Hello", pixels 132–151, line
/// 28.8: 141.5 − 14.4 = `127.1`);
/// - with one, on half the cap height above the baseline the pixels give ("xyz" in Arial, top
/// pixel 187, ink top −12.5625, cap 17.19: 199.5625 − (28.8 + 17.19) / 2 = `176.566`).
pub fn place_point_text(pix: Rect, ink: [f64; 4], baseline: f64, cap: f64, size_px: f64, line_height_px: f64) -> Point {
let left = f64::from(pix.x0) - ink[0];
// An "o" overshoots the baseline by a hair, a "g" by a fifth of the size.
let top = if ink[3] - baseline > 0.05 * size_px {
f64::from(pix.y0) - (ink[1] - baseline) - (line_height_px + cap) / 2.0
} else {
(f64::from(pix.y0) + f64::from(pix.y1)) / 2.0 - line_height_px / 2.0
};
Point::new(left, top)
}
/// [`place_point_text`] for a type layer, from its layout; `None` (placed at its pixels) when
/// there is nothing to measure: no pixels or ink, no font, or type that is turned, scaled,
/// warped or vertical.
fn point_text_origin(t: &TextLayer, pix: Rect, dpi: f32, family: &str, size_pt: f32, line_height: f64) -> Option<Point> {
let [a, b, c, d, _, _] = t.transform.m;
if pix.is_empty() || a != 1.0 || b != 0.0 || c != 0.0 || d != 1.0 || t.warp.is_some() || t.orientation != Orientation::Horizontal {
return None;
}
let size_px = f64::from(size_pt) * f64::from(dpi) / 72.0;
let cap_layer = TextLayer { text: "H".into(), font_family: family.into(), size_pt, ..Default::default() };
let mut eng = photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner);
let layout = eng.layout(t, dpi);
let ink = photocraft_text::render::ink_bounds(&layout)?;
let baseline = f64::from(layout.lines.first()?.baseline);
let cap_layout = eng.layout(&cap_layer, dpi);
let cap = f64::from(cap_layout.lines.first()?.baseline) - photocraft_text::render::ink_bounds(&cap_layout)?[1];
// Photoshop works with the line height it writes, three decimals of the size.
let line_height_px = (line_height * 1000.0).round() / 1000.0 * size_px;
let at = place_point_text(pix, ink, baseline, cap, size_px, line_height_px);
(at.x.is_finite() && at.y.is_finite()).then_some(at)
}
/// The box of a group's rule: its artboard, else the canvas (measured: a group holding a 50 × 30
/// layer writes the 400 × 300 canvas).
fn group_bounds(doc: &Document, l: &Layer) -> Rect {
let r = photocraft_doc::comps::position_bounds(l);
if r.is_empty() { doc.bounds() } else { r }
}
/// The rule for one layer, `z` its place in the stack from the bottom (1-based); `None` for a
/// layer CSS can't describe (adjustments, fill layers without a shape) or one with nothing to
/// place. A group's rule is its box alone; [`copy_css`] adds the rules of its layers.
pub fn rule(doc: &Document, z: usize, l: &Layer) -> Option<String> {
let px_per_pt = f64::from(doc.resolution_dpi.max(1.0)) / 72.0;
let mut props: Vec<(&str, String)> = Vec::new();
let mut sized = true;
let mut bounds = photocraft_doc::comps::position_bounds(l);
// Where the rule starts when it isn't where the layer's pixels start.
let mut origin: Option<Point> = None;
if !has_css(l) {
return None;
}
match &l.content {
LayerContent::Adjustment(_) => return None,
LayerContent::Group(_) => bounds = group_bounds(doc, l),
LayerContent::Text(t) => {
let style = t.runs.first().map(|r| &r.style);
let size_pt = style.map_or(t.size_pt, |s| s.size_pt);
let family = style.map(|s| s.font_family.as_str()).filter(|f| !f.is_empty()).unwrap_or(&t.font_family);
let color = style.map_or(t.color, |s| s.color);
let paragraph = t.paragraphs.first().map(|p| p.style.clone()).unwrap_or_default();
// Auto leading is the paragraph's multiple of the size (1.2 by default).
let line_height = match style.and_then(|s| s.leading_pt) {
Some(leading) if size_pt > 0.0 => f64::from(leading / size_pt),
_ => f64::from(paragraph.auto_leading),
};
let align = match paragraph.align {
TextAlign::Left => "left",
TextAlign::Center => "center",
TextAlign::Right => "right",
_ => "justify",
};
props.push(("font-size", format!("{}px", number(f64::from(size_pt) * px_per_pt))));
props.push(("font-family", quoted(family)));
props.push(("color", rgb(&color)));
props.push(("line-height", number(line_height)));
props.push(("text-align", align.into()));
match t.shape {
// Photoshop places paragraph text at its box, moved down by an explicit leading,
// and sizes it by its text, not the box.
TextShape::Box { x, y, .. } => {
let at = t.transform.apply(Point::new(f64::from(x), f64::from(y)));
let leading = style.and_then(|s| s.leading_pt).map_or(0.0, |v| f64::from(v) * px_per_pt);
origin = Some(Point::new(at.x, at.y + leading));
}
// Point text has no box of its own: only its position.
_ => {
sized = false;
origin = point_text_origin(t, bounds, doc.resolution_dpi.max(1.0), family, size_pt, line_height);
}
}
}
LayerContent::Shape(sh) => {
// A live rounded rectangle's corners, before the fill as Photoshop writes them: one
// value when all four are equal, else top-left, top-right, bottom-right, bottom-left.
// Scaled unequally, its corners are elliptical though it keeps one radius each: none.
// A live ellipse fills its box, which half the box's size on each axis rounds to.
match &sh.live {
Some(live @ LiveShape::Rect { radii, .. }) if radii.iter().any(|&r| r > 0.0) && draws(live, &sh.path) => {
let px = |r: f64| format!("{}px", number(r.max(0.0)));
let all = if radii.iter().all(|&r| r == radii[0]) { px(radii[0]) } else { radii.map(px).join(" ") };
props.push(("border-radius", all));
}
Some(LiveShape::Ellipse { .. }) => props.push(("border-radius", "50%".into())),
_ => {}
}
match &sh.fill {
Some(Fill::Solid(c)) => props.push(("background-color", rgb(c))),
_ => props.push(("background-image", image(l))),
}
}
LayerContent::Fill(f) => {
// Only a fill layer with a vector mask (a shape) gets here: placed at its outline.
if bounds.is_empty() {
let outline = l.vector_mask.as_ref().and_then(|m| m.path.control_bounds());
bounds = outline.map_or(Rect::EMPTY, |(x0, y0, x1, y1)| {
Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32).intersect(&doc.bounds())
});
}
match f {
Fill::Solid(c) => props.push(("background-color", rgb(c))),
_ => props.push(("background-image", image(l))),
}
}
_ => props.push(("background-image", image(l))),
}
if bounds.is_empty() {
return None;
}
if l.opacity < 1.0 {
props.push(("opacity", number(f64::from(l.opacity.max(0.0)))));
}
props.push(("position", "absolute".into()));
let at = origin.unwrap_or(Point::new(f64::from(bounds.x0), f64::from(bounds.y0)));
props.push(("left", format!("{}px", position(at.x))));
props.push(("top", format!("{}px", position(at.y))));
if sized {
props.push(("width", format!("{}px", number(f64::from(bounds.width())))));
props.push(("height", format!("{}px", number(f64::from(bounds.height())))));
}
props.push(("z-index", z.to_string()));
let mut out = format!(".{} {{\n", class_name(&l.name));
for (k, v) in props {
out.push_str(&format!(" {k}: {v};\n"));
}
out.push_str("}\n");
Some(out)
}
fn copy_css(s: &mut Session, p: &Value) -> Result<Value> {
let p = p.as_object().ok_or_else(|| bad("expected an object"))?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let ids = match p.get("layer") {
None | Some(Value::Null) => st.selected_layers(),
Some(v) => vec![LayerId(v.as_u64().ok_or_else(|| bad("`layer` must be an unsigned integer"))?)],
};
if ids.is_empty() {
return Err(bad("no layer selected"));
}
let walk = st.doc.walk();
for id in &ids {
if !walk.iter().any(|(_, _, l)| l.id == *id) {
return Err(EngineError::NoLayer(*id));
}
}
let mut z = HashMap::new();
stack_places(&st.doc.layers, &mut 0, &mut z, 0);
// In Layers panel order, top first: a group, then its layers (measured).
let mut picked = Vec::new();
panel_order(&st.doc.layers, false, &ids, &mut picked, 0);
let rules: Vec<(u64, String)> = picked.into_iter().filter_map(|l| z.get(&l.id).and_then(|&z| rule(&st.doc, z, l)).map(|r| (l.id.0, r))).collect();
if rules.is_empty() {
return Err(EngineError::Other("Copy CSS needs a pixel, type, shape or group layer with content".into()));
}
// Photoshop writes a group's rules one after another, with no blank line between them.
let css: String = rules.iter().map(|(_, r)| r.as_str()).collect();
Ok(json!({"css": css, "layers": rules.iter().map(|(id, _)| id).collect::<Vec<_>>()}))
}
/// Every layer's `z-index`, counted from the bottom: a group's layers come first, after one place
/// for the group's end, then the group (measured: Background 1, group end 2, its layer 3, the
/// group 4, the layer above it 5).
fn stack_places(layers: &[Layer], n: &mut usize, out: &mut HashMap<LayerId, usize>, depth: usize) {
for l in layers {
if let Some(children) = l.children() {
*n += 1;
if depth < MAX_DEPTH {
stack_places(children, n, out, depth + 1);
}
}
*n += 1;
out.insert(l.id, *n);
}
}
/// The layers whose rules are copied, top first: the selected ones and everything inside a
/// selected group, each once.
fn panel_order<'a>(layers: &'a [Layer], inside_picked: bool, ids: &[LayerId], out: &mut Vec<&'a Layer>, depth: usize) {
for l in layers.iter().rev() {
let take = inside_picked || ids.contains(&l.id);
if take {
out.push(l);
}
if let Some(children) = l.children().filter(|_| depth < MAX_DEPTH) {
panel_order(children, take, ids, out, depth + 1);
}
}
}
pub fn specs() -> Vec<CommandSpec> {
vec![CommandSpec {
id: ID,
label: "Copy CSS",
menu: &["Layer"],
shortcut: None,
params: r#"{"layer":id?} (no layer: the selected layers) → {"css": text, "layers": [id…]}; the app puts the text on the clipboard"#,
enabled,
run: copy_css,
journal: false,
}]
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,346 @@
use super::*;
use photocraft_doc::Layer;
use photocraft_geom::Rect;
/// A 400 × 300 document at 72 ppi with a 200 × 140 pixel layer at (100, 80) named `name`.
fn session(name: &str) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
s.execute("layer.new.layer", json!({"name": name})).unwrap();
s.edit("paint", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(100, 80, 300, 220), &[0.16, 0.35, 0.78, 1.0]);
Ok(())
})
.unwrap();
s
}
/// Photoshop 2025 copies this for a 200 × 140 pixel layer at (100, 80), second from the bottom.
#[test]
fn a_pixel_layer_copies_as_photoshop_writes_it() {
let mut s = session("Box");
let r = s.execute(ID, json!({})).unwrap();
assert_eq!(
r["css"],
json!(
".Box {\n background-image: url(\"Box.png\");\n position: absolute;\n left: 100px;\n top: 80px;\n width: 200px;\n height: 140px;\n z-index: 2;\n}\n"
)
);
// Photoshop: a name with spaces keeps them in the image name and turns them to `_` in the
// class; an opacity under 100 % follows the background.
let mut s = session("My Box 2");
s.edit("opacity", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().opacity = 128.0 / 255.0;
Ok(())
})
.unwrap();
let css = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.starts_with(".My_Box_2 {\n background-image: url(\"My Box 2.png\");\n opacity: 0.502;\n position: absolute;\n"), "{css}");
}
#[test]
fn fill_and_type_layers_describe_their_colour_and_font() {
let doc = session("Box").active().unwrap().doc.clone();
// Photoshop: a solid colour gives `background-color`. A fill layer is a shape with a vector
// mask, placed at its outline; without one it has no rule (Copy CSS is greyed out, measured).
let mut fill = Layer::new("Card", LayerContent::Fill(Fill::Solid(photocraft_color::Color::rgb(1.0, 120.0 / 255.0, 30.0 / 255.0))));
assert!(rule(&doc, 4, &fill).is_none());
fill.vector_mask = Some(photocraft_doc::VectorMask::new(photocraft_vector::shapes::rect(250.0, 200.0, 120.0, 60.0)));
assert_eq!(
rule(&doc, 4, &fill).unwrap(),
".Card {\n background-color: rgb(255, 120, 30);\n position: absolute;\n left: 250px;\n top: 200px;\n width: 120px;\n height: 60px;\n z-index: 4;\n}\n"
);
// A type layer: size, family, colour, auto leading and alignment, then only its position
// (Photoshop writes no size for point text). Its position is where its pixels are.
let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
cache.fill_rect(Rect::new(49, 28, 120, 52), &[0.0, 0.0, 0.0, 1.0]);
let text = photocraft_doc::TextLayer {
font_family: "Inter".into(),
size_pt: 24.0,
color: photocraft_color::Color::rgb(0.0, 0.0, 0.0),
cache: Some(cache),
..Default::default()
};
let title = Layer::new("Title", LayerContent::Text(text));
let css = rule(&doc, 3, &title).unwrap_or_default();
assert_eq!(
css,
".Title {\n font-size: 24px;\n font-family: \"Inter\";\n color: rgb(0, 0, 0);\n line-height: 1.2;\n text-align: left;\n position: absolute;\n left: 49px;\n top: 28px;\n z-index: 3;\n}\n"
);
// A group's own rule is its box, the canvas.
let group = Layer::group("Group 1", Vec::new());
assert_eq!(
rule(&doc, 5, &group).unwrap(),
".Group_1 {\n position: absolute;\n left: 0px;\n top: 0px;\n width: 400px;\n height: 300px;\n z-index: 5;\n}\n"
);
}
/// Measured: Layer › Copy CSS on a group holding a 50 × 30 layer "2nd-Box" at (10, 20) writes the
/// group's canvas box, then the layer, with no blank line; the group's end takes a place in the
/// stack, so the layer is 3 and the group 4 above the Background.
#[test]
fn a_group_writes_its_box_then_its_layers() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 400, "height": 300})).unwrap();
s.execute("layer.new.layer", json!({"name": "2nd-Box"})).unwrap();
s.edit("paint", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 20, 60, 50), &[0.16, 0.35, 0.78, 1.0]);
Ok(())
})
.unwrap();
s.execute("layer.groupLayers", json!({})).unwrap();
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
s.edit("paint", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(300, 200, 320, 220), &[0.16, 0.35, 0.78, 1.0]);
Ok(())
})
.unwrap();
let group = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.children().is_some()).unwrap().2.id.0;
let css = s.execute(ID, json!({"layer": group})).unwrap()["css"].as_str().unwrap().to_string();
let rest = css.split_once(' ').unwrap().1;
assert_eq!(
rest,
"{\n position: absolute;\n left: 0px;\n top: 0px;\n width: 400px;\n height: 300px;\n z-index: 4;\n}\n\
._2nd_Box {\n background-image: url(\"2nd-Box.png\");\n position: absolute;\n left: 10px;\n top: 20px;\n width: 50px;\n height: 30px;\n z-index: 3;\n}\n"
);
let css = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.starts_with(".Top {\n") && css.contains(" z-index: 5;\n"), "{css}");
}
/// Measured: Copy CSS is greyed out for a Solid Color fill layer without a shape.
#[test]
fn copy_css_is_off_for_a_fill_layer_without_a_shape() {
let mut s = session("Box");
assert!(s.is_enabled(ID));
s.execute("layer.newFillLayer.solidColor", json!({})).unwrap();
assert!(!s.is_enabled(ID), "a plain fill layer has no CSS");
assert!(s.execute(ID, json!({})).is_err());
}
/// Point type as Photoshop placed it (measured: text bounds and pixel bounds from its scripting
/// interface, then the copied CSS).
#[test]
fn point_type_is_placed_as_photoshop_places_it() {
let arial_cap = 1467.0 / 2048.0 * 24.0;
let times_cap = 1356.0 / 2048.0 * 24.0;
let css = |pix: Rect, ink: [f64; 4], cap: f64, size: f64, line_height: f64| {
let at = place_point_text(pix, ink, 0.0, cap, size, line_height * size);
(position(at.x), position(at.y))
};
let s = |a: &str, b: &str| (a.to_string(), b.to_string());
// "Hello", Arial 24 at (50, 150).
assert_eq!(css(Rect::new(52, 132, 104, 151), [1.875, -17.25, 53.71875, 0.1875], arial_cap, 24.0, 1.2), s("50.125", "127.1"));
// The same at 48 px.
assert_eq!(css(Rect::new(53, 65, 158, 101), [3.75, -34.5, 107.4375, 0.375], arial_cap * 2.0, 48.0, 1.2), s("49.25", "54.2"));
// With a 40 pt leading: line-height 1.667.
assert_eq!(css(Rect::new(202, 82, 254, 101), [1.875, -17.25, 53.71875, 0.1875], arial_cap, 24.0, 1.667), s("200.125", "71.496"));
// "x": no descender.
assert_eq!(css(Rect::new(300, 237, 312, 250), [0.1875, -12.5625, 11.8799, 0.0], arial_cap, 24.0, 1.2), s("299.812", "229.1"));
// Descenders: "xyz", "xg", "Hg" in Arial, "Hg" and "xg" in Times New Roman.
assert_eq!(css(Rect::new(50, 187, 86, 205), [0.1875, -12.5625, 35.71875, 4.875], arial_cap, 24.0, 1.2), s("49.812", "176.566"));
assert_eq!(css(Rect::new(330, 237, 354, 255), [0.1875, -12.75, 23.6953, 4.875], arial_cap, 24.0, 1.2), s("329.812", "226.754"));
assert_eq!(css(Rect::new(302, 262, 329, 285), [1.875, -17.25, 29.0273, 4.875], arial_cap, 24.0, 1.2), s("300.125", "256.254"));
assert_eq!(css(Rect::new(50, 84, 79, 106), [0.375, -15.9375, 28.5, 5.0625], times_cap, 24.0, 1.2), s("49.625", "77.592"));
assert_eq!(css(Rect::new(150, 89, 174, 106), [0.1875, -11.0625, 23.5, 5.0625], times_cap, 24.0, 1.2), s("149.812", "77.717"));
}
#[test]
fn positions_are_cut_after_three_decimals() {
assert_eq!(position(49.8125), "49.812");
assert_eq!(position(141.5 - 14.4), "127.1");
assert_eq!(position(100.0), "100");
assert_eq!(position(f64::INFINITY), "0");
}
/// Photoshop 2025, paragraph text in a 200 × 120 box at (60, 40) that wraps to two lines whose
/// pixels span 156 × 51: `left: 59.937px; top: 36.948px; width: 156px; height: 51px;`. Unlike point
/// text it has a size, that of its text (not the box), and it's placed at its box, not where its
/// first pixel is; an explicit leading moves it down by that much (36 px: `top: 72.948px`).
#[test]
fn paragraph_text_is_placed_at_its_box_and_sized_by_its_text() {
let doc = session("Box").active().unwrap().doc.clone();
let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
cache.fill_rect(Rect::new(62, 44, 218, 95), &[0.0, 0.0, 0.0, 1.0]);
let mut text = photocraft_doc::TextLayer {
text: "Hello world this wraps around".into(),
font_family: "Inter".into(),
size_pt: 24.0,
cache: Some(cache),
shape: photocraft_doc::text::TextShape::Box { x: 0.0, y: 0.0, width: 200.0, height: 120.0 },
transform: photocraft_geom::Affine::translate(60.0, 40.0),
..Default::default()
};
let css = rule(&doc, 3, &Layer::new("Para", LayerContent::Text(text.clone()))).unwrap_or_default();
assert_eq!(
css,
".Para {\n font-size: 24px;\n font-family: \"Inter\";\n color: rgb(0, 0, 0);\n line-height: 1.2;\n text-align: left;\n position: absolute;\n left: 60px;\n top: 40px;\n width: 156px;\n height: 51px;\n z-index: 3;\n}\n"
);
let style = photocraft_doc::text::CharStyle { font_family: "Inter".into(), size_pt: 24.0, leading_pt: Some(36.0), ..Default::default() };
text.runs = vec![photocraft_doc::text::TextRun { len: text.text.len(), style }];
let css = rule(&doc, 3, &Layer::new("Para", LayerContent::Text(text))).unwrap_or_default();
assert!(
css.contains(" line-height: 1.5;\n text-align: left;\n position: absolute;\n left: 60px;\n top: 76px;\n width: 156px;\n height: 51px;\n"),
"{css}"
);
}
#[test]
fn numbers_and_names_are_written_as_photoshop_does() {
assert_eq!(number(48.9374), "48.937");
assert_eq!(number(27.6), "27.6");
assert_eq!(number(100.0), "100");
assert_eq!(number(-0.0001), "0");
assert_eq!(number(f64::NAN), "0");
assert_eq!(class_name("My Box 2"), "My_Box_2");
assert_eq!(class_name(""), "layer");
}
/// Photoshop 2025: a class can't start with a digit, so a layer named "2nd Box" gets a `_` in
/// front; a hyphen becomes `_` like the other punctuation ("-2x" is `._2x`, "my-box" `.my_box`).
#[test]
fn class_names_never_start_with_a_digit() {
for (name, class) in [("2nd Box", "._2nd_Box {\n"), ("-2x", "._2x {\n"), ("my-box", ".my_box {\n")] {
let css = session(name).execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.starts_with(class), "{name}: {css}");
}
}
/// Names go into quoted CSS strings: a `"`, a backslash or a line break in one is escaped, so the
/// string doesn't end early and keeps the name (Photoshop writes them unescaped, which breaks
/// the rule). Ordinary names are written as before.
#[test]
fn names_in_quoted_values_are_escaped() {
let css = session("Say \"hi\"").execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" background-image: url(\"Say \\\"hi\\\".png\");\n"), "{css}");
let css = session("a\\b\nc").execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" background-image: url(\"a\\\\b\\a c.png\");\n"), "{css}");
let doc = session("Box").active().unwrap().doc.clone();
let mut cache = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8);
cache.fill_rect(Rect::new(49, 28, 120, 52), &[0.0, 0.0, 0.0, 1.0]);
let text = photocraft_doc::TextLayer { font_family: "My \"Font\"".into(), size_pt: 24.0, cache: Some(cache), ..Default::default() };
let css = rule(&doc, 3, &Layer::new("Title", LayerContent::Text(text))).unwrap_or_default();
assert!(css.contains(" font-family: \"My \\\"Font\\\"\";\n"), "{css}");
}
#[test]
fn bad_params_and_layers_without_css_are_errors() {
let mut s = session("Box");
assert!(s.execute(ID, json!({"layer": "x"})).is_err());
assert!(s.execute(ID, json!({"layer": 999_999})).is_err());
assert!(s.execute(ID, json!([])).is_err());
s.execute("layer.new.group", json!({})).unwrap();
assert!(s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().contains(" width: 400px;\n"), "an empty group writes its box");
let mut empty = Session::new();
assert!(empty.execute(ID, json!({})).is_err(), "no document");
}
/// A live rounded rectangle gives its corners as Photoshop writes them, before the fill: one
/// value when all four are equal, else top-left, top-right, bottom-right, bottom-left; a sharp
/// one writes none.
#[test]
fn a_rounded_rectangle_writes_its_border_radius() {
let mut s = session("Box");
let id = s.execute("shape.create", json!({"kind": "roundedRect", "rect": [40, 30, 120, 80], "radius": 12, "fill": "#ff0000"})).unwrap()["layer"]
.as_u64()
.unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" {\n border-radius: 12px;\n background-color: rgb(255, 0, 0);\n position: absolute;\n"), "{css}");
s.execute("shape.edit", json!({"layer": id, "radii": [20, 0, 10.5, 5]})).unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" border-radius: 20px 0px 10.5px 5px;\n background-color: rgb(255, 0, 0);\n"), "{css}");
s.execute("shape.edit", json!({"layer": id, "radii": [0, 0, 0, 0]})).unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(!css.contains("border-radius") && css.contains(" background-color: rgb(255, 0, 0);\n"), "{css}");
// Scaled 2× on both axes, its corners are twice as round.
s.execute("shape.edit", json!({"layer": id, "radii": [12, 12, 12, 12]})).unwrap();
s.execute("shape.edit", json!({"layer": id, "transform": [2, 0, 0, 2, 0, 0]})).unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" border-radius: 24px;\n background-color: rgb(255, 0, 0);\n"), "{css}");
}
/// Scaled 200 % across and 100 % down, a rounded rectangle's corners are 24 × 12 px ellipses, but
/// it keeps one radius per corner (12): no `border-radius` rather than a circular one. A flipped
/// one, whose outline runs the other way, keeps its circular corners and writes them.
#[test]
fn an_unequally_scaled_rounded_rectangle_writes_no_border_radius() {
let mut s = session("Box");
let create = json!({"kind": "roundedRect", "rect": [40, 30, 120, 80], "radius": 12, "fill": "#ff0000"});
let id = s.execute("shape.create", create.clone()).unwrap()["layer"].as_u64().unwrap();
s.execute("shape.edit", json!({"layer": id, "transform": [2, 0, 0, 1, 0, 0]})).unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(!css.contains("border-radius") && css.contains(" {\n background-color: rgb(255, 0, 0);\n"), "{css}");
let flipped = s.execute("shape.create", create).unwrap()["layer"].as_u64().unwrap();
s.execute("shape.edit", json!({"layer": flipped, "transform": [-1, 0, 0, 1, 400, 0]})).unwrap();
let css = s.execute(ID, json!({"layer": flipped})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" {\n border-radius: 12px;\n background-color: rgb(255, 0, 0);\n"), "{css}");
}
/// A live ellipse writes `border-radius: 50%;` where a rounded rectangle writes its radii, so the
/// rule draws an ellipse, not a rectangle; other live shapes (a star here) write no geometry.
#[test]
fn an_ellipse_writes_a_half_border_radius() {
let mut s = session("Box");
let id = s.execute("shape.create", json!({"kind": "ellipse", "rect": [40, 30, 120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
assert!(css.contains(" {\n border-radius: 50%;\n background-color: rgb(255, 0, 0);\n position: absolute;\n"), "{css}");
let star = s.execute("shape.create", json!({"kind": "star", "rect": [40, 30, 120, 80], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
let css = s.execute(ID, json!({"layer": star})).unwrap()["css"].as_str().unwrap().to_string();
assert!(!css.contains("border-radius") && css.contains(" {\n background-color: rgb(255, 0, 0);\n"), "{css}");
}
/// `css` without its double-quoted strings (escapes inside them skipped).
fn outside_strings(css: &str) -> String {
let (mut out, mut quoted, mut escaped) = (String::new(), false, false);
for c in css.chars() {
match (quoted, escaped, c) {
(true, true, _) => escaped = false,
(true, false, '\\') => escaped = true,
(_, false, '"') => quoted = !quoted,
(false, _, _) => out.push(c),
_ => {}
}
}
out
}
/// A name with a comment closer can't end a comment or break the rule: outside the quoted image
/// name there is no `*/`, and the class is sanitised.
#[test]
fn a_comment_closer_in_a_name_stays_inside_the_string() {
let css = session("a */ b").execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert!(!outside_strings(&css).contains("*/"), "{css}");
assert!(css.starts_with(".a____b {\n background-image: url(\"a */ b.png\");\n"), "{css}");
}
/// Layer effects aren't written: a layer with a drop shadow gives the same rule as without it,
/// placed and sized by its pixels, not the shadow.
#[test]
fn a_layer_with_a_drop_shadow_writes_its_rule_without_the_effect() {
let mut s = session("Box");
let plain = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
s.edit("fx", |doc, active| {
let l = doc.layer_mut(active.unwrap()).unwrap();
l.effects.enabled = true;
l.effects.items.push(photocraft_doc::effects::Effect::default_drop_shadow());
Ok(())
})
.unwrap();
let css = s.execute(ID, json!({})).unwrap()["css"].as_str().unwrap().to_string();
assert_eq!(css, plain);
assert!(!css.contains("shadow"), "{css}");
}
/// Real point type goes through its layout: "Hello" at a baseline of 150 is placed by its line
/// box, which starts above its first pixel (Photoshop: 127.1 for pixels from 132), not at it.
#[test]
fn point_type_is_placed_by_its_line_box() {
let mut s = session("Box");
let id = s.execute("type.create", json!({"x": 50, "y": 150, "text": "Hello", "size": 24})).unwrap()["layer"].as_u64().unwrap();
let doc = &s.active().unwrap().doc;
let pix = photocraft_doc::comps::position_bounds(doc.walk().into_iter().find(|(_, _, l)| l.id.0 == id).unwrap().2);
let css = s.execute(ID, json!({"layer": id})).unwrap()["css"].as_str().unwrap().to_string();
let value = |key: &str| css.split(&format!(" {key}: ")).nth(1).and_then(|v| v.split("px;").next()).and_then(|v| v.parse::<f64>().ok()).unwrap();
let (left, top) = (value("left"), value("top"));
assert!((left - 50.0).abs() < 1.0, "left at the origin, within the pixel rounding: {css}");
assert!(top < f64::from(pix.y0) - 2.0 && top > 150.0 - 28.8, "top {top} above the pixels at {}: {css}", pix.y0);
}
@@ -45,10 +45,10 @@ fn edits_preserve_mask_pixels_and_layer_at_all_depths_with_undo_redo() {
assert_eq!(s.active().unwrap().active_layer, Some(background));
assert_eq!(s.active().unwrap().history.entries().len(), count + 1);
// Properties invalidate the composite as far as their undo would (the masked layer is
// empty here; the adjustment reaches everything).
// empty here, and the adjustment reaches only what lies beneath it: nothing, #9329).
let damage = s.active().unwrap().last_damage;
assert_eq!(damage, crate::layer_multi_cmds::step_damage(&before, &s.active().unwrap().doc));
assert_eq!(damage.is_none(), adjustment);
assert_eq!(damage, Some(Rect::EMPTY), "adjustment: {adjustment}");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(*s.active().unwrap().doc, *before);
s.execute("edit.redo", json!({})).unwrap();
+2 -2
View File
@@ -20,9 +20,9 @@ mod selection;
mod structure;
use align::{align, distribute};
pub(crate) use damage::grow_hint;
#[cfg(any(test, debug_assertions))]
pub(crate) use damage::hint_misses;
pub(crate) use damage::note_insert;
pub(crate) use damage::{hint_misses, small_change_pct};
pub use damage::{layer_bounds, same_pixels, selection_only_change, step_damage};
use moves::link_groups;
pub(crate) use moves::shift_surface;
+270 -54
View File
@@ -1,6 +1,7 @@
use photocraft_color::{PixelFormat, SampleType};
use photocraft_compose::Ancestors;
use super::{Document, Layer, LayerContent, Rect, Session, VideoData};
use super::{Document, Layer, LayerContent, LayerId, Rect, VideoData};
/// Calls `f` with the rect of every tile that differs between two surfaces of the same format and
/// default pixel: a tile only one side has, or a different copy-on-write tile pointer at the same
@@ -237,7 +238,8 @@ fn doc_pixels_equal(a: &Document, b: &Document) -> bool {
clipping_path: _,
quick_mask,
quick_mask_unselected: _,
patterns,
// Compared by `patterns_pixels_equal`.
patterns: _,
color_table,
duotone,
layer_comps: _,
@@ -264,11 +266,57 @@ fn doc_pixels_equal(a: &Document, b: &Document) -> bool {
(Some(x), Some(y)) => alpha_channels_equal(x, y),
_ => false,
}
&& *patterns == b.patterns
&& patterns_pixels_equal(a, b)
&& *color_table == b.color_table
&& *duotone == b.duotone
}
/// Whether `a`'s and `b`'s pattern libraries composite the same. Layers draw a pattern only
/// through a reference that `photocraft_doc::pattern::find` resolves (fill and shape layers,
/// Pattern Overlay, pattern strokes and glows, Bevel textures), so patterns appended after an
/// unchanged prefix change nothing unless some reference now resolves differently: to an
/// appended pattern where it resolved to an earlier one or to none. A same-named addition that
/// loses to an existing id match changes nothing. Pattern Stamp copies its pattern into the
/// document this way on first use; the pixels it paints are a raster change, diffed by tile like
/// any other.
fn patterns_pixels_equal(a: &Document, b: &Document) -> bool {
use photocraft_doc::effects::{Effect, FxPaint};
use photocraft_doc::{Fill, Pattern, pattern::find};
if a.patterns == b.patterns {
return true;
}
if a.patterns.len() >= b.patterns.len() || !b.patterns.starts_with(a.patterns.as_slice()) {
return false;
}
// The index a reference resolves to; the prefix is equal, so equal indices mean equal patterns.
let at = |ps: &[Pattern], id: &str, name: &str| find(ps, id, name).and_then(|p| ps.iter().position(|q| std::ptr::eq(q, p)));
let hits = |id: &str, name: &str| at(&a.patterns, id, name) != at(&b.patterns, id, name);
let fill = |f: &Fill| matches!(f, Fill::Pattern { id, name, .. } if hits(id, name));
let paint = |p: &FxPaint| matches!(p, FxPaint::Pattern { id, name, .. } if hits(id, name));
// Past a nesting depth no real document reaches, assume a reference (unequal), as
// `pixels_equal_with` does.
fn any_layer(layers: &[Layer], depth: usize, refers: &dyn Fn(&Layer) -> bool) -> bool {
depth >= 256 || layers.iter().any(|l| refers(l) || matches!(&l.content, LayerContent::Group(g) if any_layer(&g.children, depth + 1, refers)))
}
let refers = |l: &Layer| {
let effect = l.effects.items.iter().any(|e| match e {
Effect::OuterGlow(g) | Effect::InnerGlow(g) => paint(&g.paint),
Effect::Stroke(s) => paint(&s.paint),
Effect::PatternOverlay { id, name, .. } => hits(id, name),
Effect::BevelEmboss(b) => b.texture.as_ref().is_some_and(|t| hits(&t.id, &t.name)),
Effect::DropShadow(_) | Effect::InnerShadow(_) | Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } | Effect::Satin(_) => false,
});
effect
|| match &l.content {
LayerContent::Fill(f) => fill(f),
LayerContent::Shape(s) => s.fill.as_ref().is_some_and(fill) || s.stroke.as_ref().is_some_and(|st| fill(&st.paint)),
// A smart object draws its cache; its own document holds its own patterns.
LayerContent::Raster(_) | LayerContent::Group(_) | LayerContent::Adjustment(_) | LayerContent::Text(_) | LayerContent::Smart(_) => false,
}
};
!any_layer(&b.layers, 0, &refers)
}
/// Whether `a` and `b` composite to the same pixels: they differ at most in fields the
/// compositor never reads (selection, guides, paths, names, …), by the same classification as
/// [`step_damage`] but without computing any bounds. Cheap: pixels compare by tile pointer.
@@ -384,9 +432,9 @@ pub fn selection_only_change(a: &Document, b: &Document) -> bool {
/// [`one_sided_bounds`]); one that draws nothing ([`inert_at`]) changes nothing. `None`
/// (composite everything) when the step touched anything the layer walk cannot bound:
/// document-level fields the compositor reads (canvas size, mode, depth, profile, global light,
/// patterns, channels, palettes), layer order and kind changes, layers added or removed that
/// reach outside their own bounds, layer properties that do (clipping, excluded channels —
/// what `layer.setProps` already reports as unbounded), and video layers. Inserting a copy of a
/// patterns, channels, palettes), kind changes, reorders of clipped layers, layers added or
/// removed that reach outside their own bounds, clipping or channel exclusion on a group, and
/// video layers. A reorder damages the moved layers at both ends ([`moved_ids`]). Inserting a copy of a
/// 12 MP layer used to recomposite every layer of the document (#2883, P8/P9 in
/// `perf/budgets.toml`).
///
@@ -397,8 +445,6 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
if !doc_pixels_equal(a, b) {
return None;
}
/// The list holding a sibling list's parent group, and the group's index there.
type Outer<'d> = Option<(&'d [Layer], usize)>;
/// What the groups around a sibling list add to a change inside it: the summed reach of
/// their effects, and whether any lays effects out over its frame.
#[derive(Clone, Copy)]
@@ -406,21 +452,67 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
reach: i32,
spans_frame: bool,
}
fn walk(xs: &[Layer], ys: &[Layer], (ox, oy): (Outer, Outer), around: Around, a: &Document, b: &Document, out: &mut Rect) -> bool {
fn add(out: &mut Rect, r: Rect) {
if !r.is_empty() {
*out = if out.is_empty() { r } else { out.union(&r) };
}
}
fn walk<'d>(
xs: &'d [Layer],
ys: &'d [Layer],
(px, py): (&Ancestors<'d>, &Ancestors<'d>),
around: Around,
a: &Document,
b: &Document,
out: &mut Rect,
) -> bool {
let depth = b.depth;
// The effects of the groups around reach past a change inside them (a parent's drop shadow).
let grow = |r: Rect, canvas: Rect| if r.is_empty() { r } else { r.inflate(around.reach).intersect(&canvas) };
// So bound a change within that reach of the canvas, not on it: a layer just off the
// canvas still moves a parent's shadow onto it (group effects are built past the canvas).
let near = |canvas: Rect| canvas.inflate(around.reach);
// Pair the layers by id, stepping over layers only one side has: one that draws nothing
// changes no pixels (a new empty layer or group, #1771), any other only where it draws.
let one_sided = |layers: &[Layer], k: usize, outer: Outer, canvas: Rect, out: &mut Rect| {
let Some(r) = one_sided_bounds(layers, k, outer, canvas) else { return false };
if !r.is_empty() {
*out = if out.is_empty() { r } else { out.union(&r) };
}
let one_sided = |layers: &[Layer], k: usize, path: &Ancestors, canvas: Rect, out: &mut Rect| {
let Some(r) = one_sided_bounds(layers, k, path, depth, near(canvas)) else { return false };
add(out, grow(r, canvas));
true
};
// A reorder: the layers that moved change pixels only where they draw (or, for an
// adjustment, reach) at each end, as hiding them there and showing them here would.
let Some(moved) = moved_ids(xs, ys) else { return false };
for &id in &moved {
let (Some(xk), Some(yk)) = (xs.iter().position(|l| l.id == id), ys.iter().position(|l| l.id == id)) else { return false };
let (x, y) = (&xs[xk], &ys[yk]);
// A clipped layer changes base when it moves, and a layer moving to or from below
// clipped layers changes theirs.
let clips = |ls: &[Layer], k: usize| ls[k].clipped || ls.get(k + 1).is_some_and(|above| above.clipped);
if clips(xs, xk) || clips(ys, yk) || !contained(x, 0) || !contained(y, 0) {
return false;
}
let (Some(bx), Some(by)) = (
photocraft_compose::change_bounds_in(xs, xk, px, depth, near(a.bounds())),
photocraft_compose::change_bounds_in(ys, yk, py, depth, near(b.bounds())),
) else {
return false;
};
add(out, grow(bx, a.bounds()));
add(out, grow(by, b.bounds()));
}
let (mut i, mut j) = (0, 0);
loop {
let (x, y) = match (xs.get(i), ys.get(j)) {
(None, None) => return true,
(Some(x), Some(y)) if x.id == y.id => (x, y),
(Some(x), _) if moved.contains(&x.id) => {
i += 1;
continue;
}
(_, Some(y)) if moved.contains(&y.id) => {
j += 1;
continue;
}
_ if inert_at(ys, j) => {
j += 1;
continue;
@@ -430,20 +522,20 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
continue;
}
(_, Some(y)) if xs.iter().all(|x| x.id != y.id) => {
if !one_sided(ys, j, oy, b.bounds(), out) {
if !one_sided(ys, j, py, b.bounds(), out) {
return false;
}
j += 1;
continue;
}
(Some(x), _) if ys.iter().all(|y| y.id != x.id) => {
if !one_sided(xs, i, ox, a.bounds(), out) {
if !one_sided(xs, i, px, a.bounds(), out) {
return false;
}
i += 1;
continue;
}
// Both sides have the layer, in another order.
// Both sides have the layer, in another order (`moved_ids` pairs the rest).
_ => return false,
};
let (xk, yk) = (i, j);
@@ -452,21 +544,39 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
if x.video.is_some() || y.video.is_some() {
return false;
}
// Clipping and channel exclusion change how *other* layers render, outside this
// layer's own bounds; they have no bounded damage.
if x.clipped != y.clipped || x.excluded_channels != y.excluded_channels {
// Clipping and channel exclusion on a group change how it composites its children;
// they have no bounded damage. Channel exclusion on any other layer is per pixel where
// it draws, which its change bounds below cover.
if (x.clipped != y.clipped || x.excluded_channels != y.excluded_channels) && (x.children().is_some() || y.children().is_some()) {
return false;
}
if x.clipped != y.clipped {
// The clipped layers directly above change base too (from this layer to the one
// beneath it, or back). A group base composites differently with clipped layers
// (a pass-through one holding an adjustment then renders isolated), so not that.
let base_is_group = |ls: &[Layer], k: usize| ls[..k].iter().rev().find(|l| !l.clipped).is_some_and(|l| l.children().is_some());
if base_is_group(xs, xk) || base_is_group(ys, yk) {
return false;
}
for (ls, k, path, d) in [(xs, xk, px, a), (ys, yk, py, b)] {
for c in (k + 1..ls.len()).take_while(|&c| ls[c].clipped) {
let Some(r) = photocraft_compose::change_bounds_in(ls, c, path, depth, near(d.bounds())) else { return false };
add(out, grow(r, d.bounds()));
}
}
}
let tiles = tile_damage(x, y);
if tiles != Some(Rect::EMPTY) {
// Both sides' extents: a move changes pixels where it left and where it landed.
// A clipped adjustment reaches as far as its base (#6535).
let (Some(bx), Some(by)) =
(photocraft_compose::change_bounds_in(xs, xk, ox, a.bounds()), photocraft_compose::change_bounds_in(ys, yk, oy, b.bounds()))
else {
// A clipped adjustment reaches as far as its base (#6535). Grown by what the
// groups around reach, as any change inside them (a parent's drop shadow).
let (Some(bx), Some(by)) = (
photocraft_compose::change_bounds_in(xs, xk, px, depth, near(a.bounds())),
photocraft_compose::change_bounds_in(ys, yk, py, depth, near(b.bounds())),
) else {
return false;
};
let whole = bx.union(&by);
let whole = grow(bx, a.bounds()).union(&grow(by, b.bounds()));
// Only pixels changed: the changed tiles, grown by what the groups around reach,
// never more than the whole extents. Effects laid out over a frame repaint it
// everywhere when it moves (#4053), so then the whole extents.
@@ -474,19 +584,33 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
|| (photocraft_compose::effects::spans_frame(y)
&& photocraft_compose::effects_frame(x, a.bounds()) != photocraft_compose::effects_frame(y, b.bounds()));
let d = match tiles {
Some(t) if !frame_moved => t.inflate(around.reach).intersect(&whole.inflate(around.reach)).intersect(&b.bounds()),
Some(t) if !frame_moved => t.inflate(around.reach).intersect(&whole).intersect(&b.bounds()),
_ => whole,
};
*out = out.union(&d);
}
match (x.children(), y.children()) {
(Some(xc), Some(yc)) => {
let reach = |l: &Layer| if photocraft_compose::effects::has_effects(l) { photocraft_compose::effects::margin(l) } else { 0 };
// A change inside that moves the group's frame (a layer added, removed or
// hidden at its edge) lays effects spanning that frame out again over the
// whole group, beyond the change (#4053).
let spans = photocraft_compose::effects::spans_frame;
if (spans(x) || spans(y)) && photocraft_compose::effects_frame(x, a.bounds()) != photocraft_compose::effects_frame(y, b.bounds()) {
let (Some(bx), Some(by)) = (
photocraft_compose::change_bounds_in(xs, xk, px, depth, near(a.bounds())),
photocraft_compose::change_bounds_in(ys, yk, py, depth, near(b.bounds())),
) else {
return false;
};
add(out, grow(bx, a.bounds()));
add(out, grow(by, b.bounds()));
}
let inner = Around {
reach: around.reach.saturating_add(reach(x).max(reach(y))),
reach: around.reach.saturating_add(effects_reach(x).max(effects_reach(y))),
spans_frame: around.spans_frame || photocraft_compose::effects::spans_frame(x) || photocraft_compose::effects::spans_frame(y),
};
if !walk(xc, yc, (Some((xs, xk)), Some((ys, yk))), inner, a, b, out) {
let (qx, qy): (Vec<_>, Vec<_>) = (px.iter().copied().chain([(xs, xk)]).collect(), py.iter().copied().chain([(ys, yk)]).collect());
if !walk(xc, yc, (&qx, &qy), inner, a, b, out) {
return false;
}
}
@@ -496,7 +620,49 @@ pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
}
}
let mut out = Rect::EMPTY;
if walk(&a.layers, &b.layers, (None, None), Around { reach: 0, spans_frame: false }, a, b, &mut out) { Some(out) } else { None }
if walk(&a.layers, &b.layers, (&[], &[]), Around { reach: 0, spans_frame: false }, a, b, &mut out) { Some(out) } else { None }
}
/// The layers both sibling lists hold that changed places (`None` when the lists are too long to
/// compare): those outside a longest common subsequence of the ids both sides have, so a bring
/// forward moves one layer, not every layer it passes.
fn moved_ids(xs: &[Layer], ys: &[Layer]) -> Option<Vec<LayerId>> {
use std::collections::HashSet;
if xs.len() == ys.len() && xs.iter().zip(ys).all(|(x, y)| x.id == y.id) {
return Some(Vec::new());
}
let in_y: HashSet<LayerId> = ys.iter().map(|l| l.id).collect();
let cx: Vec<LayerId> = xs.iter().map(|l| l.id).filter(|id| in_y.contains(id)).collect();
let in_x: HashSet<LayerId> = cx.iter().copied().collect();
let cy: Vec<LayerId> = ys.iter().map(|l| l.id).filter(|id| in_x.contains(id)).collect();
if cx == cy {
return Some(Vec::new());
}
let (n, m) = (cx.len(), cy.len());
// An O(n·m) table: past a few million cells, call it unbounded instead.
if n.saturating_mul(m) > 4_000_000 {
return None;
}
let w = m + 1;
let mut t = vec![0u32; (n + 1) * w];
for i in (0..n).rev() {
for j in (0..m).rev() {
t[i * w + j] = if cx[i] == cy[j] { t[(i + 1) * w + j + 1] + 1 } else { t[(i + 1) * w + j].max(t[i * w + j + 1]) };
}
}
let (mut i, mut j, mut kept) = (0, 0, HashSet::new());
while i < n && j < m {
if cx[i] == cy[j] {
kept.insert(cx[i]);
i += 1;
j += 1;
} else if t[(i + 1) * w + j] >= t[i * w + j + 1] {
i += 1;
} else {
j += 1;
}
}
Some(cx.into_iter().filter(|id| !kept.contains(id)).collect())
}
/// How many tiles that differ between `before` and `after` (in the surfaces of layers both have)
@@ -514,9 +680,54 @@ pub(crate) fn hint_misses(before: &Document, after: &Document, hint: Rect) -> us
misses
}
/// `hint`, a command's own rect for pixels it changed in one of `doc`'s layers, grown as far as
/// [`step_damage`] grows a change there ([`grow_in_layer`], then by the effects of the groups
/// around the layer), for whichever layer that was: the hint doesn't say. A brush dab on a
/// feathered mask changes a soft ring around the dab; cut to the bare dab, the ring stayed stale.
/// Layers the compositor doesn't draw are skipped as it skips them (a hidden layer, a clipped
/// layer over a hidden base, and everything inside a hidden group): a change there shows nowhere,
/// and growing by a hidden layer's effects widened every dab elsewhere.
pub(crate) fn grow_hint(doc: &Document, hint: Rect) -> Rect {
fn walk(layers: &[Layer], reach: i32, hint: Rect, out: &mut Rect) {
let mut base_visible = true;
for l in layers {
if !l.clipped {
base_visible = l.visible;
}
if !l.visible || !base_visible {
continue;
}
let feather = l.mask.as_ref().map_or(0.0, |m| m.feather);
*out = out.union(&grow_in_layer(l, hint, feather).inflate(reach));
if let Some(children) = l.children() {
walk(children, reach.saturating_add(effects_reach(l)), hint, out);
}
}
}
let mut out = hint;
if !hint.is_empty() {
walk(&doc.layers, 0, hint, &mut out);
}
out
}
/// How far layer `l`'s own effects carry a change to its pixels: 0 without effects.
fn effects_reach(l: &Layer) -> i32 {
if photocraft_compose::effects::has_effects(l) { photocraft_compose::effects::margin(l) } else { 0 }
}
/// `r`, changed pixels of a surface layer `l` draws from, grown as far as the change can show in
/// `l`'s own render: by the `feather` (in pixels) the compositor blurs the surface by, then by
/// `l`'s effects.
fn grow_in_layer(l: &Layer, r: Rect, feather: f32) -> Rect {
let r = if feather > 0.0 { photocraft_vector::feather::grow(r, photocraft_vector::feather::feather_sigma(feather)) } else { r };
let margin = effects_reach(l);
if r.is_empty() || margin == 0 { r } else { r.inflate(margin) }
}
/// The pixels a change from layer `a` to layer `b` (the same layer on either side of a step) can
/// have changed when only the pixels of its surfaces changed: the tiles that differ
/// ([`surface_damage`]), a mask's grown by its feather, all grown by the layer's own effects.
/// ([`surface_damage`]), grown as far as each shows in the layer's render ([`grow_in_layer`]).
/// Empty when the layers render identically. `None` when anything else changed (a property, the
/// content kind, a surface's format or default pixel): the caller then takes the layer's whole
/// extents. Children of groups are not compared (the caller walks them).
@@ -524,34 +735,33 @@ fn tile_damage(a: &Layer, b: &Layer) -> Option<Rect> {
let mut tiles = Rect::EMPTY;
let only_pixels = layer_pixels_cmp(a, b, &mut |x, y, feather| {
let Some(r) = surface_damage(x, y) else { return false };
let r = if feather > 0.0 { photocraft_vector::feather::grow(r, photocraft_vector::feather::feather_sigma(feather)) } else { r };
tiles = tiles.union(&r);
// Effects are equal on both sides here (they are compared before any surface).
tiles = tiles.union(&grow_in_layer(b, r, feather));
true
});
if !only_pixels {
return None;
}
// Effects are equal on both sides here (they are compared before any surface).
let margin = if photocraft_compose::effects::has_effects(b) { photocraft_compose::effects::margin(b) } else { 0 };
Some(if tiles.is_empty() || margin == 0 { tiles } else { tiles.inflate(margin) })
only_pixels.then_some(tiles)
}
/// Neither `l` nor anything inside it is a video layer or excludes channels.
fn contained(l: &Layer, depth: usize) -> bool {
depth < 256 && l.video.is_none() && l.excluded_channels == 0 && l.children().is_none_or(|c| c.iter().all(|c| contained(c, depth + 1)))
}
/// The pixels adding or removing `layers[k]` can change, when that is bounded: its change bounds
/// (`photocraft_compose::change_bounds_in`: not for an unclipped adjustment, or a pass-through
/// group holding one; a clipped adjustment's are its base's), provided it isn't the clipping base
/// (`photocraft_compose::change_bounds_in`: an unclipped adjustment's cover the layers beneath it
/// in its isolation scope; a clipped adjustment's are its base's), provided it isn't the clipping base
/// of clipped layers above it (they would change base), and neither it nor anything inside it is
/// a video layer or excludes channels (both reach outside the layer's bounds, see
/// [`step_damage`]).
fn one_sided_bounds(layers: &[Layer], k: usize, outer: Option<(&[Layer], usize)>, canvas: Rect) -> Option<Rect> {
fn contained(l: &Layer, depth: usize) -> bool {
depth < 256 && l.video.is_none() && l.excluded_channels == 0 && l.children().is_none_or(|c| c.iter().all(|c| contained(c, depth + 1)))
}
/// a video layer (it reaches outside the layer's bounds, see [`step_damage`]) or excludes
/// channels. Channel exclusion is per pixel where the layer draws, so it doesn't actually reach
/// further (`step_damage` bounds a property change of it that way); here it stays unbounded only
/// to be conservative.
fn one_sided_bounds(layers: &[Layer], k: usize, ancestors: &Ancestors, depth: photocraft_color::SampleType, canvas: Rect) -> Option<Rect> {
let l = layers.get(k)?;
let new_base = !l.clipped && layers.get(k + 1).is_some_and(|above| above.clipped);
if new_base || !contained(l, 0) {
return None;
}
photocraft_compose::change_bounds_in(layers, k, outer, canvas)
photocraft_compose::change_bounds_in(layers, k, ancestors, depth, canvas)
}
/// Whether `layers[k]` draws nothing wherever it sits, so adding or removing it leaves the
@@ -576,12 +786,18 @@ fn inert_at(layers: &[Layer], k: usize) -> bool {
&& (l.clipped || layers.get(k + 1).is_none_or(|above| !above.clipped))
}
/// Report the pixels a command made of more than one edit changed since `before` ([`step_damage`]),
/// so the canvas recomposites only where its new layers draw instead of the whole document.
/// A single [`Session::edit`] already reports its own damage: don't call this after one (#5695).
pub(crate) fn note_insert(s: &mut Session, before: &Document) {
let Some(st) = s.active_mut() else { return };
st.last_damage = step_damage(before, &st.doc);
/// How much of the document (percent, rounded down) changed between `a` and `b`, when that is
/// some but under 25 %: what [`step_damage`] finds, which a command that reported "redraw
/// everything" (`None`) should have reported instead. `None` when nothing changed (a view-only
/// change), when it's 25 % or more, or when `step_damage` can't bound it (a canvas-size change).
#[cfg(any(test, debug_assertions))]
pub(crate) fn small_change_pct(a: &Document, b: &Document) -> Option<u64> {
let d = step_damage(a, b).filter(|d| !d.is_empty())?;
let doc = b.bounds();
let whole = u64::from(doc.width()) * u64::from(doc.height());
let changed = d.intersect(&doc);
let pct = u64::from(changed.width()) * u64::from(changed.height()) * 100 / whole.max(1);
(pct < 25).then_some(pct)
}
/// Content bounds of a layer's pixels as stored (type and shape layers: their cached render), or
@@ -152,6 +152,7 @@ pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
}
let mask_target = p.get("target").and_then(Value::as_str) == Some("mask");
let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
let mut shift = (0, 0);
let nested = s.edit("Move", |doc, _| {
let (alone, rest): (Vec<LayerId>, Vec<LayerId>) = roots.iter().partition(|id| mask_target && doc.layer(**id).is_some_and(moves_mask_alone));
let mut ids = move_targets(doc, &rest);
@@ -175,7 +176,7 @@ pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
}
// A board moved past any canvas edge grows the canvas, as a new one does (#1531, #3070).
if ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())) {
crate::artboard_cmds::fit_canvas(doc);
shift = crate::artboard_cmds::fit_canvas(doc);
}
// The Move tool carries the selection along when it moves several layers whole, as
// Photoshop does (#7538): one step, so Undo takes both back.
@@ -184,6 +185,7 @@ pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(nested)
})?;
crate::artboard_cmds::follow_shift(s, shift);
if nested.is_empty() {
return Ok(Value::Null);
}
@@ -272,6 +272,7 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul
let sel = selected(s);
let old_active = s.active().and_then(|d| d.active_layer);
let add_copy = crate::commands::layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true);
let mut shift = (0i32, 0i32);
let (copies, active) = s.edit(label, |doc, active| {
let mut copies = Vec::new();
let mut new_active = None;
@@ -281,7 +282,9 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul
let dup = crate::commands::layer_copy(doc, id, add_copy)?;
let nid = doc.insert_above(Some(id), dup);
if !in_place {
crate::artboard_cmds::place_copy(doc, nid)?;
// Each copy's shift moved the whole document, so they add up.
let (dx, dy) = crate::artboard_cmds::place_copy(doc, nid)?;
shift = (shift.0.saturating_add(dx), shift.1.saturating_add(dy));
}
if Some(id) == old_active {
new_active = Some(nid);
@@ -293,6 +296,7 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul
*active = a;
Ok((copies, a))
})?;
crate::artboard_cmds::follow_shift(s, shift);
let out = copies.iter().map(|l| l.0).collect::<Vec<_>>();
reselect(s, copies, active);
Ok(json!({"layers": out, "layer": active.map(|l| l.0)}))
+358 -14
View File
@@ -176,13 +176,13 @@ fn moves_and_layer_props_report_only_their_area() {
assert_eq!(damage(&s), Some(Rect::new(15, 7, 25, 17)));
s.execute("layer.setProps", json!({"layer": a.0, "opacity": 0.5, "blend": "Multiply"})).unwrap();
assert_eq!(damage(&s), Some(Rect::new(15, 7, 25, 17)));
// Clipping changes reach the layers around: everything.
// Clipping a pixel layer with nothing clipped to it changes only where it draws (#9329).
s.execute("layer.setProps", json!({"layer": a.0, "clipped": true})).unwrap();
assert_eq!(damage(&s), None);
// An adjustment layer changes everything beneath it.
assert_eq!(damage(&s), Some(Rect::new(15, 7, 25, 17)));
// An adjustment layer changes everything beneath it: here the Background, the canvas.
let adj = s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.setProps", json!({"layer": adj, "visible": false})).unwrap();
assert_eq!(damage(&s), None);
assert_eq!(damage(&s), Some(doc(&s).bounds()));
// The Background (opaque everywhere): everything.
let bg = doc(&s).layers[0].id;
s.execute("layer.setProps", json!({"layer": bg.0, "opacity": 0.5})).unwrap();
@@ -269,11 +269,11 @@ fn new_layers_that_change_clipping_recomposite_everything() {
based.layers.insert(under, l);
assert_eq!(step_damage(&before, &based), None);
assert_eq!(step_damage(&based, &before), None);
// An adjustment reaches every pixel below it.
// An adjustment reaches every pixel below it: here the Background, the canvas.
let mut adjusted = before.clone();
adjusted.insert_above(None, Layer::new("inv", LayerContent::Adjustment(photocraft_doc::Adjustment::Invert)));
assert_eq!(step_damage(&before, &adjusted), None);
assert_eq!(step_damage(&adjusted, &before), None);
assert_eq!(step_damage(&before, &adjusted), Some(before.bounds()));
assert_eq!(step_damage(&adjusted, &before), Some(before.bounds()));
// Empty layers draw nothing, in any blend mode.
let mut styled = before.clone();
let mut l = Layer::raster("styled", styled.pixel_format());
@@ -343,11 +343,11 @@ fn toggling_a_clipped_adjustment_damages_only_its_base() {
s.execute("layer.setProps", json!({"layer": adj.0, "visible": false})).unwrap();
assert_eq!(damage(&s), Some(base_rect));
assert_eq!(patched(&s, &shown), hidden);
// Unclipped, the adjustment still reaches the whole canvas.
// Unclipped over the Background, the adjustment still reaches the whole canvas.
s.execute("layer.setProps", json!({"layer": adj.0, "visible": true})).unwrap();
s.execute("layer.releaseClippingMask", json!({"layer": adj.0})).unwrap();
s.execute("layer.hideLayers", json!({"layer": adj.0})).unwrap();
assert_eq!(damage(&s), None);
assert_eq!(damage(&s), Some(doc(&s).bounds()));
}
}
@@ -395,6 +395,49 @@ fn clipped_adjustment_in_pass_through_clip_base_damages_its_group() {
assert_eq!(step_damage(&before, &after), Some(Rect::new(2, 1, 4, 3)));
}
/// #9329: hiding the last visible unclipped adjustment in a pass-through group that is a clip
/// base switches the group from isolated to pass-through rendering, which agrees with the old
/// pixels outside the layers beneath only up to float rounding, so it damages the group too.
#[test]
fn unclipped_adjustment_in_pass_through_clip_base_damages_its_group() {
use photocraft_doc::{Adjustment, BlendMode};
let solid = |name: &str, r: Rect, blend: BlendMode| {
let mut l = Layer::raster(name, PixelFormat::RGBA8);
l.surface_mut().unwrap().fill_rect(r, &[0.5, 0.3, 0.7, 0.6]);
l.blend = blend;
l
};
let mut before = Document::with_background(
"t",
photocraft_geom::Size::new(10, 8),
photocraft_doc::ColorMode::Rgb,
photocraft_doc::SampleType::U8,
photocraft_color::Color::WHITE,
);
before.layers.clear();
before.layers.push(solid("bg", Rect::new(0, 0, 2, 2), BlendMode::Normal));
let a = Layer::new("A", LayerContent::Adjustment(Adjustment::Invert));
let mut g = Layer::group("G", vec![solid("P", Rect::new(2, 1, 4, 3), BlendMode::Normal), a, solid("Q", Rect::new(6, 4, 8, 6), BlendMode::Multiply)]);
g.blend = BlendMode::PassThrough;
before.layers.push(g);
let mut x = solid("X", Rect::new(2, 1, 7, 5), BlendMode::Normal);
x.clipped = true;
before.layers.push(x);
let mut after = before.clone();
let LayerContent::Group(g) = &mut after.layers[1].content else { panic!("group") };
g.children[1].visible = false;
// The layers beneath A (0..4 × 0..3) and the group (2..8 × 1..6).
let r = Rect::new(0, 0, 8, 6);
assert_eq!(step_damage(&before, &after), Some(r));
assert_eq!(step_damage(&after, &before), Some(r));
assert!(unchanged_outside(&before, &after, r));
// Without the layer clipped to the group it stays pass-through: just the layers beneath.
before.layers.truncate(2);
after.layers.truncate(2);
assert_eq!(step_damage(&before, &after), Some(Rect::new(0, 0, 4, 3)));
assert!(unchanged_outside(&before, &after, Rect::new(0, 0, 4, 3)));
}
/// #2883 (P8/P9): a duplicate shares the source's tiles (no pixel copy) and recomposites only
/// where it draws; undo brings back exactly the old pixels. A copy that becomes the clipping
/// base of the layers above still recomposites everything.
@@ -1224,13 +1267,314 @@ fn undo_of_clipping_or_channel_exclusion_composites_everything() {
let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20));
let b = rect_layer(&mut s, Rect::new(12, 12, 30, 30));
select_all(&mut s, &[b]);
// Clipping reaches the layers clipped above, outside this layer's bounds.
s.execute("layer.setProps", json!({"clipped": true})).unwrap();
// #9329: on a pixel layer both are bounded: clipping by the layer (and the clipped layers
// above it), channel exclusion by the layer (per pixel where it draws).
for p in [json!({"clipped": true}), json!({"channels": [true, false, true]})] {
let before = doc(&s).clone();
s.execute("layer.setProps", p.clone()).unwrap();
let after = doc(&s).clone();
s.undo();
let r = damage(&s).unwrap_or_else(|| panic!("{p} is bounded"));
assert!(r.width() < 100 && unchanged_outside(&after, &before, r), "{p}: {r:?}");
}
// On a group they change how it composites its children: everything.
s.execute("layer.groupLayers", json!({})).unwrap();
let g = s.active().unwrap().active_layer.unwrap();
assert!(doc(&s).layer(g).unwrap().children().is_some());
s.execute("layer.setProps", json!({"layer": g.0, "clipped": true})).unwrap();
s.undo();
assert_eq!(damage(&s), None, "a clipping change recomposites everything");
s.execute("layer.setProps", json!({"channels": [true, false, true]})).unwrap();
assert_eq!(damage(&s), None, "a group's clipping change recomposites everything");
s.execute("layer.setProps", json!({"layer": g.0, "channels": [true, false, true]})).unwrap();
s.undo();
assert_eq!(damage(&s), None, "an excluded-channel change recomposites everything");
assert_eq!(damage(&s), None, "a group's excluded-channel change recomposites everything");
}
/// A new adjustment layer of `kind` (made while `s`'s selection is active, so it masks it).
fn adjustment(s: &mut Session, kind: &str) -> LayerId {
LayerId(s.execute(&format!("layer.newAdjustmentLayer.{kind}"), json!({})).unwrap()["layer"].as_u64().unwrap())
}
/// Run `id` with `p`, then undo and redo it: each step's damage is bounded, smaller than the
/// canvas, and covers every pixel it changed (`unchanged_outside`). Returns the step's damage.
fn bounded_step(s: &mut Session, id: &str, p: serde_json::Value) -> Rect {
let before = doc(s).clone();
s.execute(id, p).unwrap();
let after = doc(s).clone();
let canvas = after.bounds();
let check = |s: &Session, from: &Document, to: &Document, what: &str| {
let r = damage(s).unwrap_or_else(|| panic!("{id} {what}: bounded"));
assert!(r.width() * r.height() < canvas.width() * canvas.height(), "{id} {what}: {r:?}");
assert!(unchanged_outside(from, to, r), "{id} {what}: {r:?} misses changed pixels");
r
};
let r = check(s, &before, &after, "");
s.undo();
check(s, &after, &before, "undo");
s.redo();
check(s, &before, &after, "redo");
r
}
/// #9329, #6533: in a 32-bit document hiding a masked adjustment damages only its mask, over
/// an opaque Background too. An integer document rounds the whole backdrop after every
/// visible adjustment layer (#9033), so there it still damages the canvas.
#[test]
fn hiding_a_masked_adjustment_damages_only_its_mask() {
for depth in [32, 8] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "depth": depth})).unwrap();
let c = rect_layer(&mut s, Rect::new(50, 50, 700, 500));
s.execute("layer.setProps", json!({"layer": c.0, "opacity": 0.37})).unwrap();
let reveal = Rect::new(520, 330, 560, 370);
s.execute("select.rect", json!({"x": reveal.x0, "y": reveal.y0, "width": 40, "height": 40})).unwrap();
let adj = adjustment(&mut s, "invert");
assert!(doc(&s).layer(adj).unwrap().mask.is_some());
if depth == 32 {
let r = bounded_step(&mut s, "layer.setProps", json!({"layer": adj.0, "visible": false}));
assert!(r.contains_rect(&reveal), "{r:?}");
} else {
s.execute("layer.setProps", json!({"layer": adj.0, "visible": false})).unwrap();
assert_eq!(damage(&s), Some(doc(&s).bounds()));
}
}
}
/// #9329, #6528: Show Only This Layer, in a document whose only layer that could reach
/// everywhere was an adjustment, is bounded by where the layers draw.
#[test]
fn show_only_with_an_adjustment_is_bounded() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8, "background": "transparent"})).unwrap();
let a = rect_layer(&mut s, Rect::new(10, 10, 30, 30));
let b = rect_layer(&mut s, Rect::new(40, 20, 60, 50));
s.execute("layer.setProps", json!({"layer": b.0, "opacity": 0.37})).unwrap();
let _ = adjustment(&mut s, "invert");
let r = bounded_step(&mut s, "layer.showOnly", json!({"layer": a.0}));
assert_eq!(r, Rect::new(10, 10, 60, 50));
}
/// #9329: Bring Forward damages only where the moved layer draws, not the whole canvas.
#[test]
fn bring_forward_damages_only_the_moved_layer() {
let mut s = session(8);
let a = rect_layer(&mut s, Rect::new(10, 10, 30, 30));
let _b = rect_layer(&mut s, Rect::new(20, 20, 50, 50));
let _c = rect_layer(&mut s, Rect::new(60, 60, 70, 70));
select_all(&mut s, &[a]);
let r = bounded_step(&mut s, "layer.arrange.bringForward", json!({}));
assert_eq!(r, Rect::new(10, 10, 30, 30));
}
/// #9329: Send Backward, its undo and its redo each damage only the moved layer; an
/// adjustment moving past a layer reaches as far as the layers beneath it at either end.
#[test]
fn send_backward_undo_and_redo_are_bounded() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8, "background": "transparent"})).unwrap();
let _a = rect_layer(&mut s, Rect::new(10, 10, 30, 30));
let b = rect_layer(&mut s, Rect::new(20, 20, 50, 50));
select_all(&mut s, &[b]);
// Either layer of the swapped pair is the one that moved.
let r = bounded_step(&mut s, "layer.arrange.sendBackward", json!({}));
assert!(r == Rect::new(20, 20, 50, 50) || r == Rect::new(10, 10, 30, 30), "{r:?}");
let _c = rect_layer(&mut s, Rect::new(60, 60, 70, 70));
let adj = adjustment(&mut s, "invert");
select_all(&mut s, &[adj]);
bounded_step(&mut s, "layer.arrange.sendBackward", json!({}));
}
/// #9329: a moved group holding a video layer has no bounded damage, as the video layer itself
/// has none.
#[test]
fn bring_forward_on_a_group_holding_a_video_layer_is_unbounded() {
let mut s = session(8);
let v = rect_layer(&mut s, Rect::new(10, 10, 30, 30));
s.edit("video", |doc, _| {
let l = doc.layer_mut(v).unwrap();
let frame = l.surface().unwrap().clone();
l.video = Some(photocraft_doc::VideoData::new(vec![frame.clone(), frame], 24.0));
Ok(())
})
.unwrap();
s.execute("layer.select", json!({"layer": v.0})).unwrap();
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
let b = rect_layer(&mut s, Rect::new(20, 20, 50, 50));
assert_eq!(doc(&s).layers.iter().map(|l| l.id).skip(1).collect::<Vec<_>>(), vec![g, b]);
select_all(&mut s, &[g]);
s.execute("layer.arrange.bringForward", json!({})).unwrap();
assert_eq!(doc(&s).layers.iter().map(|l| l.id).skip(1).collect::<Vec<_>>(), vec![b, g]);
assert_eq!(damage(&s), None);
}
/// #9329: reordering inside a group with a drop shadow damages the shadow too. The moved layer
/// knocks out the one beneath it, so the group's shape, and with it the shadow, changes.
#[test]
fn a_reorder_inside_a_group_with_a_drop_shadow_damages_the_shadow() {
let mut s = session(8);
let k = rect_layer(&mut s, Rect::new(30, 30, 50, 50));
let b = rect_layer(&mut s, Rect::new(20, 20, 50, 50));
s.edit("knockout", |doc, _| {
let l = doc.layer_mut(k).unwrap();
l.advanced.knockout = photocraft_doc::Knockout::Shallow;
l.fill_opacity = 0.0;
Ok(())
})
.unwrap();
select_all(&mut s, &[k, b]);
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
s.edit("fx", |doc, _| {
doc.layer_mut(g).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow());
Ok(())
})
.unwrap();
assert_eq!(doc(&s).layer(g).unwrap().children().unwrap().iter().map(|l| l.id).collect::<Vec<_>>(), vec![k, b]);
select_all(&mut s, &[k]);
let r = bounded_step(&mut s, "layer.arrange.bringForward", json!({}));
assert!(r.contains_rect(&Rect::new(30, 30, 50, 50)), "{r:?}");
}
/// #9329: deleting a layer inside a group with a drop shadow, and adding it back on undo,
/// damages the shadow too, which reaches past the layer.
#[test]
fn adding_or_deleting_a_layer_inside_a_group_with_a_drop_shadow_damages_the_shadow() {
let mut s = session(8);
let k = rect_layer(&mut s, Rect::new(20, 20, 30, 30));
let b = rect_layer(&mut s, Rect::new(50, 40, 60, 50));
select_all(&mut s, &[k, b]);
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
s.edit("fx", |doc, _| {
doc.layer_mut(g).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow());
Ok(())
})
.unwrap();
let r = bounded_step(&mut s, "layer.delete", json!({"layer": k.0}));
assert!(r.contains_rect(&Rect::new(20, 20, 30, 30)), "{r:?}");
}
/// A group holding `layers`, with a drop shadow that reaches about 8 px down and right of them.
fn shadowed_group(s: &mut Session, layers: &[LayerId]) -> LayerId {
select_all(s, layers);
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
s.edit("fx", |doc, _| {
doc.layer_mut(g).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow());
Ok(())
})
.unwrap();
g
}
/// [`bounded_step`] for a step that must change canvas pixels, so it can't pass vacuously.
fn bounded_visible_step(s: &mut Session, id: &str, p: serde_json::Value) -> Rect {
let before = photocraft_compose::render(doc(s), doc(s).bounds());
let r = bounded_step(s, id, p);
assert_ne!(photocraft_compose::render(doc(s), doc(s).bounds()).px, before.px, "{id}: no canvas pixel changed");
r
}
/// #9329: deleting a layer just off the canvas inside a group whose drop shadow reaches onto
/// it, and adding it back on undo, damages the shadow on the canvas.
#[test]
fn deleting_an_off_canvas_layer_damages_its_group_shadow_on_the_canvas() {
let mut s = session(8);
let k = rect_layer(&mut s, Rect::new(-10, 20, -1, 30));
let b = rect_layer(&mut s, Rect::new(50, 40, 60, 50));
shadowed_group(&mut s, &[k, b]);
bounded_visible_step(&mut s, "layer.delete", json!({"layer": k.0}));
}
/// #9329: reordering a layer just off the canvas inside a group whose drop shadow reaches onto
/// it damages the shadow on the canvas. The moved layer knocks out the one beneath it, so the
/// group's shape, and with it the shadow, changes.
#[test]
fn reordering_an_off_canvas_layer_damages_its_group_shadow_on_the_canvas() {
let mut s = session(8);
let k = rect_layer(&mut s, Rect::new(-9, 25, -1, 35));
let b = rect_layer(&mut s, Rect::new(-14, 20, -1, 40));
s.edit("knockout", |doc, _| {
let l = doc.layer_mut(k).unwrap();
l.advanced.knockout = photocraft_doc::Knockout::Shallow;
l.fill_opacity = 0.0;
Ok(())
})
.unwrap();
shadowed_group(&mut s, &[k, b]);
select_all(&mut s, &[k]);
bounded_visible_step(&mut s, "layer.arrange.bringForward", json!({}));
}
/// #9329: unclipping a layer inside a group with a drop shadow exposes its pixels outside its
/// old base, which moves the group's shadow past the layer; clipping it back, on undo and redo,
/// too.
#[test]
fn clipping_and_unclipping_inside_a_shadowed_group_damages_the_shadow() {
let mut s = session(8);
let a = rect_layer(&mut s, Rect::new(20, 20, 30, 30));
let b = rect_layer(&mut s, Rect::new(25, 25, 45, 45));
s.execute("layer.setProps", json!({"layer": b.0, "clipped": true})).unwrap();
shadowed_group(&mut s, &[a, b]);
bounded_visible_step(&mut s, "layer.setProps", json!({"layer": b.0, "clipped": false}));
bounded_visible_step(&mut s, "layer.setProps", json!({"layer": b.0, "clipped": true}));
}
/// #9329: a property change on a layer inside a group with a drop shadow changes the shadow,
/// which reaches past the layer.
#[test]
fn a_property_change_inside_a_shadowed_group_damages_the_shadow() {
let mut s = session(8);
let a = rect_layer(&mut s, Rect::new(20, 20, 30, 30));
let b = rect_layer(&mut s, Rect::new(50, 40, 60, 50));
shadowed_group(&mut s, &[a, b]);
bounded_visible_step(&mut s, "layer.setProps", json!({"layer": a.0, "opacity": 0.3}));
}
/// #9329: hiding or deleting a layer at the edge of a group with a Gradient Overlay shrinks the
/// group's frame, which lays the gradient out again over the rest of the group (#4053).
#[test]
fn hiding_or_deleting_a_layer_in_a_group_with_a_gradient_overlay_damages_the_group() {
use photocraft_doc::{Effect, FxCommon, Gradient};
let mut s = session(8);
let a = rect_layer(&mut s, Rect::new(10, 10, 30, 30));
let b = rect_layer(&mut s, Rect::new(60, 40, 80, 60));
select_all(&mut s, &[a, b]);
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
s.edit("fx", |doc, _| {
doc.layer_mut(g).unwrap().effects.items.push(Effect::GradientOverlay {
common: FxCommon::new(photocraft_doc::BlendMode::Normal, 1.0),
gradient: Gradient::default(),
dither: false,
interpolation: None,
});
Ok(())
})
.unwrap();
let r = bounded_visible_step(&mut s, "layer.setProps", json!({"layer": b.0, "visible": false}));
assert!(r.contains_rect(&Rect::new(10, 10, 30, 30)), "{r:?}");
s.undo();
let r = bounded_visible_step(&mut s, "layer.delete", json!({"layer": b.0}));
assert!(r.contains_rect(&Rect::new(10, 10, 30, 30)), "{r:?}");
}
/// #9329: clipping a layer to the one beneath damages it and the layers clipped to it
/// (they change base), on undo and redo too.
#[test]
fn clipping_a_layer_damages_it_and_the_clipped_run_above() {
let mut s = session(8);
let _a = rect_layer(&mut s, Rect::new(10, 10, 40, 40));
let b = rect_layer(&mut s, Rect::new(20, 20, 60, 50));
let c = rect_layer(&mut s, Rect::new(30, 15, 70, 45));
s.execute("layer.setProps", json!({"layer": c.0, "clipped": true})).unwrap();
let r = bounded_step(&mut s, "layer.setProps", json!({"layer": b.0, "clipped": true}));
assert_eq!(r, Rect::new(20, 15, 70, 50));
}
/// #9329: excluding a channel from a pixel layer's blend damages only where it draws.
#[test]
fn excluding_a_channel_damages_only_the_layer() {
let mut s = session(8);
let _a = rect_layer(&mut s, Rect::new(10, 10, 40, 40));
let b = rect_layer(&mut s, Rect::new(20, 20, 60, 50));
let r = bounded_step(&mut s, "layer.setProps", json!({"layer": b.0, "channels": [true, false, true]}));
assert_eq!(r, Rect::new(20, 20, 60, 50));
}
#[test]
@@ -173,23 +173,71 @@ fn tile_damage_grows_by_the_layer_effect_margin() {
assert!(unchanged_outside(&before, &after, d));
}
/// The default drop shadow, `distance` px away and `size` px soft.
fn drop_shadow(distance: f32, size: f32) -> photocraft_doc::Effect {
match photocraft_doc::Effect::default_drop_shadow() {
photocraft_doc::Effect::DropShadow(sh) => photocraft_doc::Effect::DropShadow(photocraft_doc::Shadow { distance, size, ..sh }),
e => e,
}
}
/// A styled layer inside a styled group: the group's shadow is cast by the child's shadow too, so
/// a dab's change reaches as far as both shadows together, not just the farther one.
#[test]
fn a_dab_inside_a_group_with_a_drop_shadow_damages_the_shadow() {
let mut s = session(1024, 768);
let child = layer_with(&mut s, &[(Rect::new(600, 400, 700, 500), [1.0, 0.0, 0.0, 1.0])]);
let child = layer_with(&mut s, &[(Rect::new(200, 400, 300, 500), [1.0, 0.0, 0.0, 1.0])]);
s.execute("layer.select", json!({"layer": child.0})).unwrap();
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
s.edit("fx", |doc, _| {
doc.layer_mut(g).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow());
for id in [child, g] {
doc.layer_mut(id).unwrap().effects.items.push(drop_shadow(40.0, 2.0));
}
Ok(())
})
.unwrap();
assert!(photocraft_compose::effects::margin(doc(&s).layer(g).unwrap()) > 0);
let dab = Rect::new(640, 440, 660, 460);
let (before, after) = paint(&mut s, child, dab, [0.0, 0.0, 1.0, 1.0]);
assert!(photocraft_compose::effects::margin(doc(&s).layer(g).unwrap()) > 40);
// A brush dab (a hinted edit) in empty space left of a tile's right edge. Each shadow falls
// about 20 px right and 35 px down, so the group's shadow of the child's shadow lands about
// 40 px right and 70 px down, in the next tile and past either shadow's reach alone.
s.execute("layer.select", json!({"layer": child.0})).unwrap();
let before = doc(&s);
s.execute("paint.stroke", json!({"points": [[TILE_SIZE - 30, 300]], "size": 10, "hardness": 1.0, "color": "#0000ff", "layer": child.0})).unwrap();
assert_eq!(s.damage_misses, 0);
let d = damage(&s).expect("a bounded dab");
assert!(d.contains_rect(&dab), "{d:?}");
assert!(unchanged_outside(&before, &after, d), "the group's shadow changed outside {d:?}");
assert!(d.x0 < TILE_SIZE && d.x1 > TILE_SIZE, "{d:?}");
assert!(unchanged_outside(&before, &doc(&s), d), "the group's shadow changed outside {d:?}");
}
/// A layer the compositor doesn't draw adds nothing to a dab elsewhere: neither a hidden layer's
/// effects nor those of layers inside a hidden group grow the hint.
#[test]
fn a_brush_hint_ignores_the_effects_of_hidden_layers() {
let mut s = session(1024, 768);
let plain = full_layer(&mut s);
let hidden = layer_with(&mut s, &[(Rect::new(800, 600, 900, 700), [1.0, 0.0, 0.0, 1.0])]);
let child = layer_with(&mut s, &[(Rect::new(50, 600, 150, 700), [0.0, 1.0, 0.0, 1.0])]);
s.execute("layer.select", json!({"layer": child.0})).unwrap();
let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
s.edit("fx", |doc, _| {
for id in [hidden, child] {
let l = doc.layer_mut(id).unwrap();
l.effects.items.push(drop_shadow(40.0, 40.0));
}
doc.layer_mut(hidden).unwrap().visible = false;
doc.layer_mut(g).unwrap().visible = false;
Ok(())
})
.unwrap();
assert!(photocraft_compose::effects::margin(doc(&s).layer(hidden).unwrap()) > 40);
// A dab in the middle of a tile, far from every tile edge.
s.execute("layer.select", json!({"layer": plain.0})).unwrap();
let before = doc(&s);
s.execute("paint.stroke", json!({"points": [[384, 384]], "size": 10, "hardness": 1.0, "color": "#0000ff", "layer": plain.0})).unwrap();
assert_eq!(s.damage_misses, 0);
let d = damage(&s).expect("a bounded dab");
assert!(d.contains(384, 384) && d.width() <= 20 && d.height() <= 20, "grown by a hidden layer: {d:?}");
assert!(unchanged_outside(&before, &doc(&s), d));
}
#[test]
@@ -210,6 +258,12 @@ fn painting_a_clip_base_under_a_styled_clipped_layer_is_covered() {
let (before, after) = paint(&mut s, base, Rect::new(640, 440, 660, 460), [0.0, 0.0, 0.0, 0.0]);
let d = damage(&s).expect("a bounded base edit");
assert!(unchanged_outside(&before, &after, d), "the clipped layer changed outside {d:?}");
// At a tile's edge too: the clipped layer's shadow is built from its own shape, and the base
// only masks it pixel by pixel, so a base edit changes nothing past its own tiles.
let (before, after) = paint(&mut s, base, Rect::new(3 * TILE_SIZE - 6, 440, 3 * TILE_SIZE, 460), [0.0, 0.0, 0.0, 0.0]);
let d = damage(&s).expect("a bounded base edit");
assert!(d.x1 <= 3 * TILE_SIZE, "{d:?}");
assert!(unchanged_outside(&before, &after, d), "the clipped layer changed outside {d:?}");
}
/// #4053: effects laid out over the layer's frame repaint it everywhere when it grows.
@@ -269,6 +323,41 @@ fn a_hint_that_misses_a_changed_tile_is_counted() {
assert_eq!(damage(&s), Some(Rect::new(600, 400, 620, 420)));
}
/// A brush hint is the bare dab; on a feathered mask the dab changes a soft ring around it, and
/// the hint must not cut that off.
#[test]
fn a_brush_hint_on_a_feathered_mask_keeps_the_ring() {
let mut s = session(1024, 768);
let id = full_layer(&mut s);
s.edit("mask", |doc, _| {
doc.layer_mut(id).unwrap().mask = Some(photocraft_doc::LayerMask { feather: 10.0, ..photocraft_doc::LayerMask::reveal_all() });
Ok(())
})
.unwrap();
let before = doc(&s);
s.execute("paint.stroke", json!({"points": [[500, 400]], "size": 10, "hardness": 1.0, "color": "#000000", "target": "mask", "layer": id.0})).unwrap();
assert_eq!(s.damage_misses, 0);
let d = damage(&s).expect("a bounded dab");
assert!(unchanged_outside(&before, &doc(&s), d), "the feathered mask changed outside {d:?}");
}
/// The same for a layer's effects: the dab's drop shadow lands outside the dab.
#[test]
fn a_brush_hint_on_a_layer_with_a_drop_shadow_keeps_the_shadow() {
let mut s = session(1024, 768);
let id = layer_with(&mut s, &[(Rect::new(600, 400, 700, 500), [1.0, 0.0, 0.0, 1.0])]);
s.edit("fx", |doc, _| {
doc.layer_mut(id).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow());
Ok(())
})
.unwrap();
let before = doc(&s);
s.execute("paint.stroke", json!({"points": [[300, 300]], "size": 10, "hardness": 1.0, "color": "#0000ff", "layer": id.0})).unwrap();
assert_eq!(s.damage_misses, 0);
let d = damage(&s).expect("a bounded dab");
assert!(unchanged_outside(&before, &doc(&s), d), "the shadow changed outside {d:?}");
}
#[test]
fn painting_command_hints_cover_their_changed_tiles() {
let mut s = session(600, 400);
@@ -319,3 +408,195 @@ fn painting_command_hints_cover_their_changed_tiles() {
assert!(unchanged_outside(&before, &doc(&s), d), "{cmd}: pixels changed outside {d:?}");
}
}
// PR C (#9329): damage spans a command, not a revision.
/// The damage since the command began: measured from the revision before it, bounded, and
/// covering every pixel the command changed.
fn command_damage(s: &mut Session, cmd: &str, p: serde_json::Value) -> (std::sync::Arc<Document>, Rect) {
let (before, rev) = (doc(s), s.active().unwrap().revision);
s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
let st = s.active().unwrap();
assert!(st.revision - rev >= 2, "{cmd}: several revisions ({} → {})", rev, st.revision);
assert_eq!(st.damage_from(), rev, "{cmd}: measured from before the command");
let d = st.last_damage.unwrap_or_else(|| panic!("{cmd}: bounded damage"));
assert!(unchanged_outside(&before, &st.doc, d), "{cmd}: pixels changed outside {d:?}");
(before, d)
}
#[test]
fn paste_into_reports_damage_since_the_command_began() {
let mut s = session(1024, 768);
layer_with(&mut s, &[(Rect::new(0, 0, 1024, 768), [0.2, 0.4, 0.6, 1.0]), (Rect::new(40, 40, 120, 120), [0.9, 0.1, 0.1, 1.0])]);
s.execute("select.rect", json!({"x": 40, "y": 40, "width": 100, "height": 100})).unwrap();
s.execute("edit.copy", json!({})).unwrap();
s.execute("select.rect", json!({"x": 700, "y": 500, "width": 120, "height": 90})).unwrap();
let (_, d) = command_damage(&mut s, "edit.pasteSpecial.pasteInto", json!({}));
assert!(!d.intersect(&Rect::new(700, 500, 820, 590)).is_empty(), "the pasted area: {d:?}");
assert!(u64::from(d.width()) * u64::from(d.height()) * 4 < 1024 * 768, "the pasted area, not the canvas: {d:?}");
}
#[test]
fn stroke_path_damage_spans_every_subpath() {
let mut s = session(1024, 768);
layer_with(&mut s, &[(Rect::new(0, 0, 1024, 768), [0.5, 0.5, 0.5, 1.0])]);
let path = json!({"subpaths": [{"knots": [[20, 20], [80, 20], [80, 80]]}, {"knots": [[800, 600], [900, 600], [900, 700]]}]});
s.execute("path.set", json!({ "path": path })).unwrap();
// A tool with its own `paint.*` command runs once per subpath, one revision each.
let (_, d) = command_damage(&mut s, "path.stroke", json!({"tool": "burn", "size": 16}));
assert!(d.contains(50, 20) && d.contains(850, 600), "both subpaths: {d:?}");
assert_eq!(s.whole_redraws, 0);
}
/// Pattern Stamp copies its pattern into the document on first use: a pattern no layer
/// refers to draws nothing, so a multi-subpath Stroke Path stays bounded.
#[test]
fn a_new_unreferenced_pattern_keeps_stroke_path_bounded() {
let mut s = session(1024, 768);
layer_with(&mut s, &[(Rect::new(0, 0, 1024, 768), [0.5, 0.5, 0.5, 1.0])]);
let path = json!({"subpaths": [{"knots": [[20, 20], [80, 20], [80, 80]]}, {"knots": [[800, 600], [900, 600], [900, 700]]}]});
s.execute("path.set", json!({ "path": path })).unwrap();
let n = doc(&s).patterns.len();
let p = json!({"tool": "patternStamp", "size": 16, "hardness": 100, "pattern": "Checkerboard", "scale": 100, "aligned": true});
let (_, d) = command_damage(&mut s, "path.stroke", p);
assert!(doc(&s).patterns.len() > n, "the stamp added its pattern");
assert!(d.contains(50, 20) && d.contains(850, 600), "both subpaths: {d:?}");
assert_eq!(s.whole_redraws, 0);
}
/// A pattern that an existing layer refers to (here a fill layer whose pattern was missing)
/// changes that layer's pixels when it is added: not bounded by the tile diff.
#[test]
fn a_new_pattern_a_layer_refers_to_is_unbounded() {
let mut s = session(400, 300);
s.execute("layer.newFillLayer.pattern", json!({"pattern": "Checkerboard"})).unwrap();
// Without its pixel cache, so both sides render the fill from the library.
let mut with = (*doc(&s)).clone();
with.layers.iter_mut().for_each(|l| l.fill_cache = None);
let mut without = with.clone();
without.patterns.clear();
assert!(!same_pixels(&without, &with), "the fill layer draws only with its pattern");
assert_eq!(step_damage(&without, &with), None);
// Unchanged libraries, and an unreferenced addition, stay pixel-equal.
assert_eq!(step_damage(&with, &with), Some(Rect::EMPTY));
let plain = doc(&session(400, 300));
let mut more = (*plain).clone();
more.patterns = with.patterns.clone();
assert_eq!(step_damage(&plain, &more), Some(Rect::EMPTY));
assert!(unchanged_outside(&plain, &more, Rect::EMPTY));
}
/// An appended pattern sharing its name with one a layer already resolves by id loses to that id
/// match (`pattern::find` tries ids first), so the layer draws as before: bounded, not a whole
/// redraw. A cross-document layer copy can bring such a pattern along.
#[test]
fn a_same_named_new_pattern_a_reference_still_resolves_past_is_bounded() {
let mut s = session(400, 300);
s.execute("layer.newFillLayer.pattern", json!({"pattern": "Checkerboard"})).unwrap();
let mut with = (*doc(&s)).clone();
with.layers.iter_mut().for_each(|l| l.fill_cache = None);
let refers_by_id = with.layers.iter().any(|l| matches!(&l.content, LayerContent::Fill(photocraft_doc::Fill::Pattern { id, .. }) if !id.is_empty()));
assert!(refers_by_id, "the fill layer refers to its pattern by id");
let mut twin = with.patterns[0].clone();
twin.id = "another-id".into();
twin.surface.fill_rect(Rect::new(0, 0, twin.width as i32, twin.height as i32), &[1.0, 0.0, 1.0, 1.0]);
let mut more = with.clone();
more.patterns.push(twin);
assert_eq!(step_damage(&with, &more), Some(Rect::EMPTY));
assert!(unchanged_outside(&with, &more, Rect::EMPTY));
}
#[test]
fn a_failed_compound_reports_no_change() {
let mut s = session(600, 400);
let id = layer_with(&mut s, &[(Rect::new(0, 0, 50, 50), [1.0, 0.0, 0.0, 1.0])]);
let (before, rev) = (doc(&s), s.active().unwrap().revision);
let r: Result<()> = crate::analysis_cmds::compound(&mut s, "Both", |s| {
paint(s, id, Rect::new(300, 200, 340, 240), [0.0, 1.0, 0.0, 1.0]);
paint(s, id, Rect::new(10, 300, 40, 340), [0.0, 0.0, 1.0, 1.0]);
Err(EngineError::Other("the second step failed".into()))
});
assert!(r.is_err());
// What `Session::dispatch` does after any inline command.
s.note_command_damage("test.compound", &before, rev);
let st = s.active().unwrap();
assert!(same_pixels(&before, &st.doc), "rolled back");
assert_eq!((st.damage_from(), st.last_damage), (rev, Some(Rect::EMPTY)), "nothing changed since it began");
assert_eq!(s.whole_redraws, 0);
}
#[test]
fn select_then_edit_in_one_command_is_bounded() {
let mut s = session(1024, 768);
let id = layer_with(&mut s, &[(Rect::new(0, 0, 1024, 768), [0.2, 0.4, 0.6, 1.0])]);
let steps = vec![
("layer.select".to_string(), json!({"layer": id.0})),
("select.rect".to_string(), json!({"x": 300, "y": 300, "width": 50, "height": 40})),
("edit.fill".to_string(), json!({"color": "#ff0000"})),
("select.deselect".to_string(), json!({})),
];
s.actions.list.push(crate::actions_cmds::Action::new("A", steps));
let (_, d) = command_damage(&mut s, "actions.play", json!({"action": "A"}));
assert!(d.contains(300, 300) && d.contains(349, 339), "{d:?}");
assert!(u64::from(d.width()) * u64::from(d.height()) * 4 < 1024 * 768, "the filled tiles, not the canvas: {d:?}");
assert_eq!(s.whole_redraws, 0);
}
#[test]
fn whole_document_redraws_of_small_edits_are_counted() {
let mut s = session(1000, 1000);
let id = layer_with(&mut s, &[(Rect::new(0, 0, 1000, 1000), [0.2, 0.4, 0.6, 1.0])]);
// A synthetic command that paints 1 % and reports "everything".
let rev = s.active().unwrap().revision;
let (before, _) = paint(&mut s, id, Rect::new(10, 10, 110, 110), [1.0, 0.0, 0.0, 1.0]);
s.active_mut().unwrap().last_damage = None;
s.note_command_damage("test.wholeRedraw", &before, rev);
assert_eq!(s.whole_redraws, 1);
// A canvas-size change really does redraw everything: not counted.
s.execute("image.canvasSize", json!({"width": 1200, "height": 900})).unwrap();
assert_eq!(s.active().unwrap().last_damage, None);
assert_eq!(s.whole_redraws, 1);
}
#[test]
fn no_command_redraws_the_whole_document_for_a_small_edit() {
let mut s = session(1024, 768);
let base = layer_with(&mut s, &[(Rect::new(0, 0, 1024, 768), [0.2, 0.4, 0.6, 1.0])]);
let small = layer_with(&mut s, &[(Rect::new(100, 100, 160, 160), [0.9, 0.1, 0.1, 1.0])]);
let other = layer_with(&mut s, &[(Rect::new(130, 130, 190, 190), [0.1, 0.9, 0.1, 1.0])]);
let path = json!({"subpaths": [{"knots": [[20, 20], [80, 20]]}, {"knots": [[800, 600], [900, 600]]}]});
let steps: Vec<(&str, serde_json::Value)> = vec![
("layer.select", json!({"layer": base.0})),
("select.rect", json!({"x": 300, "y": 300, "width": 50, "height": 40})),
("edit.fill", json!({"color": "#ff0000"})),
("filter.blur.gaussianBlur", json!({"radius": 2})),
("edit.copy", json!({})),
("select.rect", json!({"x": 600, "y": 400, "width": 80, "height": 60})),
("edit.pasteSpecial.pasteInto", json!({})),
("edit.undo", json!({})),
("edit.redo", json!({})),
("layer.select", json!({"layer": base.0})),
("paint.stroke", json!({"points": [[100, 400], [200, 420]], "size": 20, "color": "#2040ff"})),
("edit.undo", json!({})),
("edit.redo", json!({})),
("path.set", json!({ "path": path })),
("path.stroke", json!({"tool": "pencil", "size": 4, "color": "#0000ff", "opacity": 100})),
("path.stroke", json!({"tool": "burn", "size": 16})),
("layer.select", json!({"layer": small.0})),
("layer.setProps", json!({"layer": small.0, "opacity": 0.5})),
("layer.setProps", json!({"layer": small.0, "visible": false})),
("layer.setProps", json!({"layer": small.0, "visible": true})),
("layer.translate", json!({"layer": small.0, "dx": 20, "dy": 10})),
// Show Only hides the full-canvas base: a large change, so not counted either way.
("layer.showOnly", json!({"layer": small.0})),
("layer.showOnly", json!({"layer": small.0})),
("layer.arrange.bringForward", json!({})),
("layer.arrange.sendBackward", json!({})),
("layer.setProps", json!({"layer": other.0, "clipped": true})),
("layer.new.layer", json!({})),
];
for (cmd, p) in steps {
s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
assert_eq!(s.whole_redraws, 0, "{cmd}: redrew the whole document for a small edit");
}
}
+12 -4
View File
@@ -276,7 +276,7 @@ fn raw_enabled(s: &Session) -> std::result::Result<(), String> {
let d = s.active().ok_or("no document open")?;
match d.doc.mode {
ColorMode::Rgb | ColorMode::Grayscale => Ok(()),
m => Err(format!("Camera Raw Filter needs an RGB or Grayscale document (this one is {m:?})")),
m => Err(format!("RAW Develop Filter needs an RGB or Grayscale document (this one is {m:?})")),
}
}
@@ -412,12 +412,13 @@ fn camera_raw_cmd(s: &mut Session, p: &Value) -> Result<Value> {
if raw_pixels(area).is_none() {
return Err(bad(
RAW,
format!("the image is too large for Camera Raw ({}×{} px; max {} megapixels)", area.width(), area.height(), MAX_RAW_PIXELS / 1_000_000),
format!("the image is too large for RAW Develop ({}×{} px; max {} megapixels)", area.width(), area.height(), MAX_RAW_PIXELS / 1_000_000),
));
}
}
let t0 = Stopwatch::start();
let id = run_filter(s, RAW, "Camera Raw Filter", p, p.clone(), false, &|surf, canvas| camera_raw_surface(surf, canvas.union(&surf.content_bounds()), &cr))?;
let id =
run_filter(s, RAW, "RAW Develop Filter", p, p.clone(), false, &|surf, canvas| camera_raw_surface(surf, canvas.union(&surf.content_bounds()), &cr))?;
Ok(json!({"layer": id.0, "identity": cr.is_identity(), "ms": t0.ms()}))
}
@@ -469,7 +470,7 @@ pub fn specs() -> Vec<CommandSpec> {
},
CommandSpec {
id: RAW,
label: "Camera Raw Filter…",
label: "RAW Develop Filter…",
menu: &["Filter"],
shortcut: Some("Cmd+Shift+A"),
params: r##"{"temperature":-100..100=0,"tint":-100..100=0,"exposure":-5..5=0,"contrast":-100..100=0,"highlights":-100..100=0,"shadows":-100..100=0,"whites":-100..100=0,"blacks":-100..100=0,"texture":-100..100=0,"clarity":-100..100=0,"dehaze":-100..100=0,"vibrance":-100..100=0,"saturation":-100..100=0,"curveHighlights":-100..100=0,"curveLights":-100..100=0,"curveDarks":-100..100=0,"curveShadows":-100..100=0,"curveSplits":[25,50,75],"pointCurve":[[in,out]],"pointCurveRed":[[in,out]],"pointCurveGreen":[[in,out]],"pointCurveBlue":[[in,out]],"hslHue":[8],"hslSat":[8],"hslLum":[8],"gradeShadows":{"hue":deg,"sat":0..100,"lum":-100..100},"gradeMidtones":{},"gradeHighlights":{},"gradeGlobal":{},"gradeBlending":0..100=50,"gradeBalance":-100..100=0,"shadowTint":-100..100=0,"calibrationHue":[red,green,blue] -100..100,"calibrationSat":[red,green,blue] -100..100 (the Calibration panel: Shadows tint and the primaries' hue and saturation),"sharpenAmount":0..150=0,"sharpenRadius":0.5..3=1,"sharpenDetail":0..100=25,"sharpenMasking":0..100=0,"noiseLuminance":0..100=0,"noiseLuminanceDetail":0..100=50,"noiseColor":0..100=0,"noiseColorDetail":0..100=50,"grainAmount":0..100=0,"grainSize":0..100=25,"grainRoughness":0..100=50,"vignetteAmount":-100..100=0,"vignetteMidpoint":0..100=50,"vignetteRoundness":-100..100=0,"vignetteFeather":0..100=50,"vignetteHighlights":0..100=0,"vignetteStyle":"highlightPriority|colorPriority|paintOverlay","seed":u32=0}"##,
@@ -492,6 +493,13 @@ pub fn specs() -> Vec<CommandSpec> {
#[cfg(test)]
mod tests {
#[test]
fn raw_develop_filter_keeps_its_automation_id() {
let command = super::specs().into_iter().find(|command| command.id == "filter.cameraRaw").expect("existing RAW command");
assert_eq!(command.label, "RAW Develop Filter…");
}
use super::*;
fn session(depth: u32) -> Session {
+68 -2
View File
@@ -9,6 +9,7 @@
use photocraft_algo::quantize::{self, BitmapMethod, Dither, Forced, HalftoneShape, PaletteKind};
use photocraft_algo::transform::{Homography, Interp};
use photocraft_cms::{ColorSpace, TransformOptions};
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_doc::adjust::CurvePoint;
use photocraft_doc::{ColorTable, Document, Duotone, DuotoneInk, Layer, LayerContent, LayerId, Size};
@@ -255,6 +256,56 @@ fn parse_dither(s: &str) -> Option<Dither> {
})
}
/// Convert a tool colour from the working RGB space into the samples used by the
/// flattened document. RGB and Indexed documents keep their own document profile;
/// grayscale output is a scalar sample replicated into the flattened RGB view.
fn working_matte_color(s: &Session, doc: &Document, color: [f32; 4]) -> Result<[f32; 3]> {
let destination = match crate::color_cmds::mode_space(doc.mode) {
ColorSpace::Rgb | ColorSpace::Gray => crate::color_cmds::document_profile(doc),
// CMYK and Lab flatten through the compositor's sRGB view on the pinned main path.
_ => crate::color_cmds::composite_profile(doc),
};
let source = s.color.working(ColorMode::Rgb);
let options = TransformOptions { intent: s.color.settings.intent(), bpc: s.color.settings.bpc, ..Default::default() };
let transform = photocraft_cms::transform::cached(&source, &destination, options)
.map_err(|e| bad("image.mode.indexedColor", format!("cannot convert matte colour: {e}")))?;
let mut output = [0.0; 16];
transform.eval(&color[..3], &mut output);
let matte = if destination.color_space == ColorSpace::Gray { [output[0]; 3] } else { [output[0], output[1], output[2]] };
if matte.iter().any(|v| !v.is_finite()) {
return Err(bad("image.mode.indexedColor", "cannot convert matte colour to finite document samples"));
}
Ok(matte.map(|v| v.clamp(0.0, 1.0)))
}
fn indexed_matte(s: &Session, p: &Value) -> Result<Option<[f32; 3]>> {
const CMD: &str = "image.mode.indexedColor";
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
let matte = match p.get("matte") {
None | Some(Value::Null) => return Ok(None),
Some(Value::String(value)) => match value.as_str() {
"none" => return Ok(None),
"white" => [1.0; 3],
"black" => [0.0; 3],
"gray" => [128.0 / 255.0; 3],
"netscapeGray" => [192.0 / 255.0; 3],
"foreground" => working_matte_color(s, doc, s.tools.foreground)?,
"background" => working_matte_color(s, doc, s.tools.background)?,
value if value.len() == 7 && value.starts_with('#') => p
.get("matte")
.and_then(parse_color)
.ok_or_else(|| bad(CMD, "matte must be none, foreground, background, white, black, gray, netscapeGray or #rrggbb"))?
.map(|v| f32::from(v) / 255.0),
_ => return Err(bad(CMD, "matte must be none, foreground, background, white, black, gray, netscapeGray or #rrggbb")),
},
_ => return Err(bad(CMD, "matte must be a colour string")),
};
if matte.iter().any(|v| !v.is_finite() || !(0.0..=1.0).contains(v)) {
return Err(bad(CMD, "matte channels must be finite and in 0..=1"));
}
Ok(Some(matte))
}
fn indexed_color(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "image.mode.indexedColor";
let kind = PaletteKind::from_id(str_or(p, "palette", "selective"))
@@ -273,8 +324,23 @@ fn indexed_color(s: &mut Session, p: &Value) -> Result<Value> {
};
let amount = num(p, "amount", 75.0).clamp(0.0, 100.0) / 100.0;
let transparency = p.get("transparency").and_then(Value::as_bool).unwrap_or(true);
let matte = indexed_matte(s, p)?;
let (pal_len, transparent) = s.edit("Indexed Color", |doc, active| {
let mut px = composite(doc, !transparency);
let mut px = composite(doc, !transparency && matte.is_none());
if let Some(matte) = matte {
for pixel in &mut px {
let alpha = pixel[3].clamp(0.0, 1.0);
if alpha == 1.0 {
continue;
}
if !transparency || alpha > 0.0 {
for (channel, background) in pixel[..3].iter_mut().zip(matte) {
*channel = *channel * alpha + background * (1.0 - alpha);
}
pixel[3] = 1.0;
}
}
}
let has_clear = transparency && px.iter().any(|q| q[3] < 0.5);
let mut pal = quantize::build_palette(&px, kind, if has_clear { colors.saturating_sub(1).max(2) } else { colors }, forced).map_err(|e| bad(CMD, e))?;
let transparent = if has_clear && pal.len() < 256 {
@@ -689,7 +755,7 @@ pub fn specs() -> Vec<CommandSpec> {
"image.mode.indexedColor",
"Indexed Color…",
["Image", "Mode"],
r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens)"##,
r##"{"palette":"selective|perceptual|adaptive|exact|systemMac|systemWindows|web|uniform"="selective","colors":2..256=256,"forced":"blackWhite|none|primaries|web"="blackWhite","transparency":bool=true,"matte":color,"dither":"diffusion|none|pattern|noise"="diffusion","amount":0..100=75} (flattens; matte: none|foreground|background|white|black|gray|netscapeGray|#rrggbb; gray=50% Gray (#808080), netscapeGray=Netscape Gray (#c0c0c0))"##,
|s| mode_is(
s,
&[ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Indexed, ColorMode::Duotone, ColorMode::Cmyk, ColorMode::Lab],
+154
View File
@@ -247,6 +247,160 @@ fn indexed_color_palettes_and_dithers() {
}
}
#[test]
fn indexed_exact_preserves_profile_and_samples_through_default_rgb() {
for depth in [8, 16, 32] {
for profile in ["adobe-rgb-compat", "display-p3", "prophoto-compat", "none"] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 1, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
s.execute("edit.assignProfile", json!({"profile": profile})).unwrap();
paint(&mut s, |_, _| [100.0 / 255.0, 150.0 / 255.0, 200.0 / 255.0, 1.0]);
let source_profile = doc(&s).icc_profile.clone();
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})).unwrap();
assert_eq!(doc(&s).icc_profile, source_profile, "{profile} at {depth}-bit: Indexed profile");
assert_eq!(doc(&s).color_table.as_ref().unwrap().colors, vec![[100, 150, 200]]);
let indexed_pixel = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
s.execute("image.mode.rgb", json!({})).unwrap();
assert_eq!(doc(&s).mode, ColorMode::Rgb);
assert_eq!(doc(&s).icc_profile, source_profile, "{profile} at {depth}-bit: RGB profile");
assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), indexed_pixel);
assert!(doc(&s).color_table.is_none());
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(doc(&s).mode, ColorMode::Indexed);
assert_eq!(doc(&s).icc_profile, source_profile);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(doc(&s).mode, ColorMode::Rgb);
assert_eq!(doc(&s).icc_profile, source_profile);
s.execute("edit.undo", json!({})).unwrap();
s.execute("image.mode.rgb", json!({"profile": "srgb"})).unwrap();
assert_eq!(doc(&s).icc_profile, Some(photocraft_cms::Builtin::Srgb.profile().to_bytes()), "an explicit target still converts");
if profile != "none" {
assert_ne!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), indexed_pixel);
}
}
}
}
#[test]
fn indexed_matte_blends_edges_without_replacing_clear_pixels() {
for depth in [8, 16, 32] {
for (matte, color) in [
("black", [0.0, 0.0, 0.0]),
("white", [1.0, 1.0, 1.0]),
("#0000ff", [0.0, 0.0, 1.0]),
("foreground", [0.0, 0.0, 1.0]),
("background", [0.0, 1.0, 0.0]),
] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 4, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
s.execute("tools.setColors", json!({"foreground": "#0000ff", "background": "#00ff00"})).unwrap();
paint(&mut s, |x, _| match x {
0 => [0.0, 1.0, 0.0, 1.0],
1 => [1.0, 0.0, 0.0, 0.75],
2 => [1.0, 0.0, 0.0, 0.25],
_ => [0.0; 4],
});
let source = [1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0));
let expected = source.map(|pixel| [0, 1, 2].map(|i| pixel[i] * pixel[3] + color[i] * (1.0 - pixel[3])));
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap();
let surface = doc(&s).layers[0].surface().unwrap();
let edges = [1, 2].map(|x| surface.rgba(x, 0));
for (edge, expected) in edges.iter().zip(expected) {
for i in 0..3 {
assert!((edge[i] - expected[i]).abs() <= 1.0 / 255.0, "{depth}-bit {matte}: {edge:?} vs {expected:?}");
}
assert_eq!(edge[3], 1.0);
}
assert_eq!(surface.rgba(3, 0)[3], 0.0, "{matte}: fully transparent pixels stay clear");
assert_eq!(surface.rgba(0, 0), [0.0, 1.0, 0.0, 1.0]);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!([1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0)), source);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!([1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0)), edges);
}
}
}
#[test]
fn indexed_matte_converts_working_rgb_to_document_profile_at_every_depth() {
use photocraft_cms::Transform;
for depth in [8, 16, 32] {
for (matte, color) in [("foreground", [0.0, 1.0, 0.0]), ("background", [1.0, 0.0, 0.0])] {
for (intent, bpc) in [("relative", false), ("absolute", true)] {
let mut s = Session::new();
s.execute("edit.colorSettings", json!({"workingRgb": "display-p3", "intent": intent, "bpc": bpc})).unwrap();
s.execute("file.new", json!({"width": 2, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap();
s.execute("tools.setColors", json!({"foreground": "#00ff00", "background": "#ff0000"})).unwrap();
paint(&mut s, |x, _| if x == 0 { [1.0, 0.0, 0.0, 0.5] } else { [0.0; 4] });
let pixel = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
let profile = doc(&s).icc_profile.clone();
let source = s.color.working(ColorMode::Rgb);
let destination = crate::color_cmds::document_profile(doc(&s));
let transform = Transform::new(&source, &destination, s.color.settings.intent(), bpc).unwrap();
let mut converted = [0.0; 16];
transform.eval(&color, &mut converted);
let expected = [0, 1, 2].map(|i| ((pixel[i] * pixel[3] + converted[i].clamp(0.0, 1.0) * (1.0 - pixel[3])) * 255.0).round() as u8);
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap();
let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
assert_eq!([edge[0], edge[1], edge[2]].map(|v| (v * 255.0).round() as u8), expected, "{depth}-bit {matte} {intent}, bpc={bpc}");
assert_eq!(edge[3], 1.0);
assert_eq!(doc(&s).icc_profile, profile);
assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(1, 0)[3], 0.0);
}
}
}
}
#[test]
fn indexed_matte_hex_stays_in_document_rgb_coordinates() {
for depth in [8, 16, 32] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 1, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap();
paint(&mut s, |_, _| [1.0, 0.0, 0.0, 0.5]);
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": "#3366cc"})).unwrap();
let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
let expected = [0.5 + 0.5 * 0.2, 0.5 * 0.4, 0.5 * 0.8];
for (got, want) in edge[..3].iter().zip(expected) {
assert!((got - want).abs() <= 2.0 / 255.0, "{depth}-bit: {edge:?} vs {expected:?}");
}
assert_eq!(edge[3], 1.0);
}
}
#[test]
fn indexed_matte_named_gray_choices_use_their_document_samples() {
for (matte, channel) in [("gray", 128.0 / 255.0), ("netscapeGray", 192.0 / 255.0)] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 1, "height": 1, "depth": 32, "background": "transparent"})).unwrap();
paint(&mut s, |_, _| [1.0, 0.0, 0.0, 0.5]);
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap();
let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
assert!((edge[0] - (0.5 + channel * 0.5)).abs() <= 1.0 / 255.0, "{matte}: {edge:?}");
for value in edge[1..3].iter() {
assert!((*value - channel * 0.5).abs() <= 2.0 / 255.0, "{matte}: {edge:?}");
}
assert_eq!(edge[3], 1.0);
}
}
#[test]
fn indexed_matte_without_transparency_fills_clear_pixels_and_rejects_bad_input_atomically() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 2, "height": 1, "background": "transparent"})).unwrap();
let before = s.active().unwrap().revision;
for matte in [json!(false), json!(12), json!("#gg0000"), json!("#000000ff"), json!("unknown")] {
assert!(s.execute("image.mode.indexedColor", json!({"matte": matte})).is_err(), "{matte}");
assert_eq!(s.active().unwrap().revision, before);
assert_eq!(doc(&s).mode, ColorMode::Rgb);
}
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false, "matte": "#0000ff"})).unwrap();
assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(doc(&s).color_table.as_ref().unwrap().transparent, None);
}
#[test]
fn indexed_exact_transparency_and_sources() {
// Two colours + transparency: exact palette with a transparent entry.
+34 -11
View File
@@ -22,14 +22,33 @@ fn has_notes(s: &Session) -> std::result::Result<(), String> {
if s.active().is_some_and(|d| !d.doc.notes.is_empty()) { Ok(()) } else { Err("the document has no notes".into()) }
}
/// PDF-style date (`D:YYYYMMDDhhmmssZ`) as Photoshop stores in notes; empty without a clock.
/// Photoshop's default note colour (#11795): RGB 255, 255, 131 (stored as 16-bit 0x8383 blue).
pub const DEFAULT_NOTE_COLOR: [f32; 3] = [1.0, 1.0, 131.0 / 255.0];
/// The PDF date (`D:YYYYMMDDHHMMSS+HH'mm'`) Photoshop stores in a note: local time with its
/// offset from UTC (#11795), through chrono. Empty without a clock (the web build).
fn pdf_date() -> String {
let iso = crate::analysis_cmds::now_iso();
if iso.len() < 19 {
return String::new();
#[cfg(not(target_arch = "wasm32"))]
{
let now = chrono::Local::now();
pdf_date_at(&now.with_timezone(now.offset()))
}
let digits: String = iso[..19].chars().filter(char::is_ascii_digit).collect();
format!("D:{digits}Z")
#[cfg(target_arch = "wasm32")]
{
String::new()
}
}
/// [`pdf_date`] for the moment `at`: its own wall-clock time and UTC offset.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) fn pdf_date_at<Tz: chrono::TimeZone>(at: &chrono::DateTime<Tz>) -> String
where
Tz::Offset: std::fmt::Display,
{
use chrono::Offset;
let off = at.offset().fix().local_minus_utc();
let (sign, off) = if off < 0 { ('-', -off) } else { ('+', off) };
format!("D:{}{sign}{:02}'{:02}'", at.format("%Y%m%d%H%M%S"), off / 3600, off % 3600 / 60)
}
pub fn note_json(i: usize, n: &Note) -> Value {
@@ -44,7 +63,8 @@ fn color_of(cmd: &str, p: &Value) -> Result<Option<Color>> {
if p.get("color").is_none() {
return Ok(None);
}
let c = crate::commands::color_param(cmd, p, "color", [1.0, 1.0, 0.51, 1.0])?;
let [r, g, b] = DEFAULT_NOTE_COLOR;
let c = crate::commands::color_param(cmd, p, "color", [r, g, b, 1.0])?;
Ok(Some(Color::rgb(c[0], c[1], c[2])))
}
@@ -65,10 +85,11 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
author: p.get("author").and_then(Value::as_str).unwrap_or("").to_string(),
text: p.get("text").and_then(Value::as_str).unwrap_or("").to_string(),
position: [x, y],
popup: [x + 20.0, y + 20.0, x + 260.0, y + 160.0],
// Photoshop's popup: 240 × 140, at the icon's top-left + (8, 10) (#11795).
popup: [x + 8.0, y + 10.0, x + 248.0, y + 150.0],
color: Color::rgb(DEFAULT_NOTE_COLOR[0], DEFAULT_NOTE_COLOR[1], DEFAULT_NOTE_COLOR[2]),
open: p.get("open").and_then(Value::as_bool).unwrap_or(true),
modified: pdf_date(),
..Default::default()
};
if let Some(c) = color_of(CMD, p)? {
n.color = c;
@@ -131,7 +152,8 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("all").and_then(Value::as_bool) == Some(true) {
let n = s.active().map_or(0, |d| d.doc.notes.len());
s.edit("Delete All Notes", |d, _| {
// Photoshop's name for the step, with a lower-case "all" (#11791).
s.edit("Delete all Notes", |d, _| {
d.notes.clear();
Ok(())
})?;
@@ -270,7 +292,8 @@ mod tests {
let d = s.active().unwrap().doc.clone();
assert_eq!(d.notes[0].text, "fixed");
assert_eq!(d.notes[0].position, [20.0, 12.0]);
assert_eq!(d.notes[0].popup[0], 40.0);
// The popup travels with its icon: 20 + 8 (#11795).
assert_eq!(d.notes[0].popup[0], 28.0);
// Unchanged edits don't add history.
let before = s.active().unwrap().history.past_len();
assert_eq!(s.execute("notes.set", json!({"index": 0, "text": "fixed"})).unwrap()["changed"], false);
@@ -0,0 +1,116 @@
//! #11795: what a new note stores, as in Photoshop: colour 255, 255, 131, a 240 × 140 popup at the
//! icon's top-left + (8, 10), and a local-time PDF date with its offset. Document operations move
//! the popup with its icon and keep its size.
use chrono::{FixedOffset, TimeZone};
use serde_json::json;
use super::notes_cmds::{DEFAULT_NOTE_COLOR, pdf_date_at};
use crate::Session;
fn session(w: u32, h: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": w, "height": h, "background": "white"})).unwrap();
s
}
fn note(s: &Session, i: usize) -> photocraft_doc::Note {
s.active().unwrap().doc.notes[i].clone()
}
#[test]
fn a_new_note_has_the_default_colour_and_popup() {
let mut s = session(600, 400);
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
let n = note(&s, 0);
let rgb = n.color.to_rgb();
assert_eq!(rgb.map(|v| (v * 255.0).round() as i32), [255, 255, 131], "{rgb:?}");
assert_eq!(DEFAULT_NOTE_COLOR.map(|v| (v * 65535.0).round() as u32), [0xffff, 0xffff, 0x8383], "the 16-bit components Photoshop saves");
assert_eq!(n.popup, [108.0, 110.0, 348.0, 250.0], "icon + (8, 10), 240 × 140");
// A note on the pasteboard keeps its popup there too.
s.execute("notes.add", json!({"x": -178, "y": 300})).unwrap();
assert_eq!(note(&s, 1).popup, [-170.0, 310.0, 70.0, 450.0]);
// An explicit colour still wins.
s.execute("notes.add", json!({"x": 10, "y": 10, "color": [0.25, 0.5, 1.0]})).unwrap();
assert_eq!(note(&s, 2).color.to_rgb(), [0.25, 0.5, 1.0]);
}
#[test]
fn the_date_is_local_time_with_its_offset() {
let at = |offset: i32| FixedOffset::east_opt(offset).unwrap().with_ymd_and_hms(2026, 11, 6, 20, 14, 55).unwrap();
assert_eq!(pdf_date_at(&at(3600)), "D:20261106201455+01'00'");
assert_eq!(pdf_date_at(&at(0)), "D:20261106201455+00'00'");
assert_eq!(pdf_date_at(&at(-(5 * 3600 + 30 * 60))), "D:20261106201455-05'30'");
// A new note's own date has that shape.
let mut s = session(100, 100);
s.execute("notes.add", json!({"x": 10, "y": 10})).unwrap();
let d = note(&s, 0).modified;
let b = d.as_bytes();
assert!(d.len() == 23 && d.starts_with("D:") && matches!(b[16], b'+' | b'-') && b[19] == b'\'' && b[22] == b'\'', "{d}");
assert!(d[2..16].chars().all(|c| c.is_ascii_digit()), "{d}");
}
#[test]
fn image_size_moves_the_icon_and_keeps_the_popup_size() {
let mut s = session(600, 400);
s.execute("notes.add", json!({"x": 100, "y": 99})).unwrap();
let before = note(&s, 0);
s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap();
let n = note(&s, 0);
assert_eq!(n.position, [50.0, 49.5], "the icon point scales as today");
let size = |p: [f64; 4]| [p[2] - p[0], p[3] - p[1]];
assert_eq!(size(n.popup), size(before.popup), "240 × 140 still");
assert_eq!([n.popup[0] - n.position[0], n.popup[1] - n.position[1]], [8.0, 10.0], "still at icon + (8, 10)");
}
#[test]
fn canvas_size_and_a_quarter_turn_keep_the_popup_size() {
let mut s = session(600, 400);
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
s.execute("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})).unwrap();
let n = note(&s, 0);
assert_eq!(n.position, [0.0, 50.0], "moved by the canvas offset");
assert_eq!(n.popup, [8.0, 60.0, 248.0, 200.0]);
s.execute("image.imageRotation.90cw", json!({})).unwrap();
let r = note(&s, 0);
assert_eq!([r.popup[2] - r.popup[0], r.popup[3] - r.popup[1]], [240.0, 140.0], "a turn doesn't swap the popup's sides");
}
#[test]
fn a_mode_change_leaves_notes_alone() {
let mut s = session(100, 100);
s.execute("notes.add", json!({"x": 10, "y": 20})).unwrap();
let before = note(&s, 0);
s.execute("image.mode.cmyk", json!({})).unwrap();
assert_eq!(note(&s, 0), before);
}
#[test]
fn a_turn_keeps_todays_popup_origin_and_the_popup_size() {
// Where the popup sits after a turn wasn't measured (#11795), so it keeps today's origin (the
// top-left of the turned rectangle) and only the size rule applies.
let mut s = session(600, 400);
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
// The popup [108, 110, 348, 250] turned 90° clockwise on a 400 px tall canvas spans x 150..290,
// y 108..348; it starts there and stays 240 × 140.
s.execute("image.imageRotation.90cw", json!({})).unwrap();
assert_eq!(note(&s, 0).popup, [150.0, 108.0, 390.0, 248.0]);
// A flip keeps today's mirrored popup, which already has its size.
let mut s = session(600, 400);
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
s.execute("image.imageRotation.flipCanvasHorizontal", json!({})).unwrap();
assert_eq!(note(&s, 0).popup, [252.0, 110.0, 492.0, 250.0]);
}
#[test]
fn an_unset_popup_stays_unset_under_image_size() {
// An all-zero popup means "none stored": PSD export writes its default popup for it, so Image
// Size must not turn it into a 0 × 0 rectangle somewhere else.
let mut s = session(600, 400);
let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
doc.notes.push(photocraft_doc::Note { position: [100.0, 100.0], ..Default::default() });
s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap();
let n = note(&s, 0);
assert_eq!(n.position, [50.0, 50.0]);
assert_eq!(n.popup, [0.0; 4]);
}
+12 -6
View File
@@ -12,7 +12,7 @@
//! editable equivalent for them. Vector masks, paths, notes, slices and guides follow the affine
//! map closest to the homography (exact when the quad is a parallelogram).
use photocraft_algo::transform::{Homography, Interp, convex_quad, quad_size, quad_to_rect, warp_surface_clipped};
use photocraft_algo::transform::{Homography, Interp, convex_quad, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped};
use photocraft_color::PixelFormat;
use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size};
use photocraft_geom::{Affine, Rect};
@@ -60,8 +60,9 @@ fn corners(p: &Value) -> Result<[[f64; 2]; 4]> {
}
/// Output size: `width`/`height` in whole px; one alone keeps the quad's proportions; neither
/// takes the quad's mean side lengths ([`quad_size`]).
fn out_size(p: &Value, q: &[[f64; 2]; 4]) -> Result<(u32, u32)> {
/// takes the rectangle the quad shows in perspective ([`quad_free_size`], `center` being the
/// document's centre).
fn out_size(p: &Value, q: &[[f64; 2]; 4], center: [f64; 2]) -> Result<(u32, u32)> {
let side = |key: &str| -> Result<Option<f64>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
@@ -77,7 +78,7 @@ fn out_size(p: &Value, q: &[[f64; 2]; 4]) -> Result<(u32, u32)> {
(Some(w), Some(h)) => (w, h),
(Some(w), None) => (w, w * qh / qw),
(None, Some(h)) => (h * qw / qh, h),
(None, None) => (qw, qh),
(None, None) => quad_free_size(q, center),
};
let px = |v: f64| -> Result<u32> {
let v = v.round().max(1.0);
@@ -216,7 +217,8 @@ fn map_samplers(points: &[[f64; 2]], h: &Homography, (w, ht): (u32, u32)) -> Vec
fn perspective_crop(s: &mut Session, p: &Value) -> Result<Value> {
let q = corners(p)?;
let (w, h) = out_size(p, &q)?;
let center = s.active().map_or([0.0; 2], |d| [f64::from(d.doc.size.width) / 2.0, f64::from(d.doc.size.height) / 2.0]);
let (w, h) = out_size(p, &q, center)?;
let res = resolution(p)?;
let interp = interpolation(p)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
@@ -259,13 +261,17 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Perspective Crop",
menu: &[],
shortcut: None,
params: r##"{"corners":[[x,y],[x,y],[x,y],[x,y]] (top-left, top-right, bottom-right, bottom-left; a convex quad, document px),"width":px,"height":px,"resolution":ppi,"interpolation":"bicubic|bilinear|nearest"="bicubic"} → {width,height,resolution,corners} (the quad is mapped onto an upright width x height canvas, all layers, one undo step; no width/height: the quad's mean side lengths, one alone keeps its proportions; type, shape, fill and smart object layers are rasterized)"##,
params: r##"{"corners":[[x,y],[x,y],[x,y],[x,y]] (top-left, top-right, bottom-right, bottom-left; a convex quad, document px),"width":px,"height":px,"resolution":ppi,"interpolation":"bicubic|bilinear|nearest"="bicubic"} → {width,height,resolution,corners} (the quad is mapped onto an upright width x height canvas, all layers, one undo step; no width/height: the rectangle the quad shows in perspective, one alone keeps its proportions; type, shape, fill and smart object layers are rasterized)"##,
enabled: has_doc,
run: perspective_crop,
journal: true,
}]
}
#[cfg(test)]
#[path = "perspective_crop_size_tests.rs"]
mod perspective_crop_size_tests;
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,146 @@
//! #11798: with W and H empty, a Perspective Crop takes the size of the rectangle the quad shows
//! in perspective. The expected sizes are the reference application's measurements from the issue.
use photocraft_algo::transform::{convex_quad, quad_free_size};
use serde_json::{Value, json};
use crate::Session;
const SKEWED: [[f64; 2]; 4] = [[100.0, 50.0], [700.0, 80.0], [760.0, 450.0], [40.0, 420.0]];
const PAST_CANVAS: [[f64; 2]; 4] = [[100.0, 50.0], [872.0, 50.0], [872.0, 550.0], [100.0, 450.0]];
const RECTANGLE: [[f64; 2]; 4] = [[100.0, 50.0], [700.0, 50.0], [700.0, 450.0], [100.0, 450.0]];
const CENTER: [f64; 2] = [400.0, 250.0];
/// The size an 800 x 500 document commits to.
fn commit(corners: [[f64; 2]; 4], options: Value) -> (u32, u32) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 500, "background": "white"})).unwrap();
let mut p = json!({"corners": corners});
p.as_object_mut().unwrap().extend(options.as_object().unwrap().clone());
s.execute("image.perspectiveCrop", p).unwrap();
let size = s.active().unwrap().doc.size;
(size.width, size.height)
}
fn assert_near((w, h): (u32, u32), (want_w, want_h): (u32, u32)) {
assert!(w.abs_diff(want_w) <= 1 && h.abs_diff(want_h) <= 1, "{w} x {h}, want {want_w} x {want_h} (within 1 px)");
}
/// The size comes from the perspective, so it is larger than the skewed quad's edges.
#[test]
fn a_skewed_quad_takes_the_measured_size() {
assert_near(commit(SKEWED, json!({})), (731, 588));
}
/// One pair of parallel sides leaves the perspective undefined: the longest edges are measured.
#[test]
fn a_quad_with_parallel_sides_past_the_canvas_takes_the_measured_size() {
assert_near(commit(PAST_CANVAS, json!({})), (778, 500));
}
#[test]
fn a_rectangular_quad_keeps_its_own_size() {
assert_eq!(commit(RECTANGLE, json!({})), (600, 400));
}
/// A size set on the options bar is not affected, for either kind of quad.
#[test]
fn width_and_height_are_still_exact() {
for corners in [SKEWED, RECTANGLE] {
assert_eq!(commit(corners, json!({"width": 400, "height": 300, "resolution": 144})), (400, 300));
}
}
/// One side alone still follows the proportions of the quad's mean edges.
#[test]
fn one_side_alone_keeps_the_mean_edge_proportions() {
assert_eq!(commit(SKEWED, json!({"width": 661})), (661, 375));
assert_eq!(commit(SKEWED, json!({"height": 375})), (661, 375));
}
/// A click or two off a rectangle must not swing the proportions (the estimate is unstable there).
#[test]
fn a_nearly_rectangular_quad_stays_near_its_edges() {
for e in [0.25, 0.5, 1.0, 2.0] {
for q in [
[[100.0, 50.0], [700.0 + e, 50.0], [700.0, 450.0 + e], [100.0 - e, 450.0]],
[[100.0, 50.0], [700.0 + e, 50.0 + e], [700.0, 450.0 + e], [100.0 - e, 450.0]],
] {
let (w, h) = quad_free_size(&q, CENTER);
assert!((w - 600.0).abs() <= 2.0 * e + 1.0 && (h - 400.0).abs() <= 2.0 * e + 1.0, "offset {e}: {w} x {h}");
}
}
}
fn longest_edges([tl, tr, br, bl]: [[f64; 2]; 4]) -> (f64, f64) {
let len = |a: [f64; 2], b: [f64; 2]| (b[0] - a[0]).hypot(b[1] - a[1]);
(len(tl, tr).max(len(bl, br)), len(tl, bl).max(len(tr, br)))
}
/// One pixel on one corner used to take this quad across the parallel-sides limit, and the output
/// from 602 x 400 to 719 x 289. Both sides of that limit now keep the edges.
#[test]
fn a_pixel_of_click_error_cannot_swing_the_proportions() {
for x in [697.0, 698.0] {
let q = [[100.0, 50.0], [700.0, 50.0], [x, 384.0], [100.0, 450.0]];
assert_eq!(quad_free_size(&q, CENTER), longest_edges(q), "bottom right at x = {x}");
}
}
/// A 600 x 400 rectangle turned by `yaw` and `pitch` degrees, as a camera of focal length `focal`
/// centred on the image sees it.
fn photographed(focal: f64, yaw: f64, pitch: f64) -> [[f64; 2]; 4] {
let ((sy, cy), (sp, cp)) = (yaw.to_radians().sin_cos(), pitch.to_radians().sin_cos());
[[-300.0, -200.0], [300.0, -200.0], [300.0, 200.0], [-300.0, 200.0]].map(|[x, y]: [f64; 2]| {
let (px, py, pz) = (cy * x, sy * sp * x + cp * y, -sy * cp * x + sp * y);
let k = focal / (pz + focal * 1.2);
[CENTER[0] + px * k, CENTER[1] + py * k]
})
}
/// Where the sides converge enough to measure, a known rectangle's proportions come back exactly;
/// where they barely converge, the longest edges are used instead.
#[test]
fn a_photographed_rectangle_keeps_its_proportions() {
for focal in [600.0, 1000.0, 1600.0] {
for (yaw, pitch) in [(20.0, 15.0), (30.0, 10.0), (-25.0, 20.0), (15.0, -30.0), (3.0, 2.0)] {
let (w, h) = quad_free_size(&photographed(focal, yaw, pitch), CENTER);
assert!((w / h - 1.5).abs() < 1e-3, "focal {focal}, {yaw} / {pitch} degrees: {w} x {h}");
}
let barely = photographed(focal, 1.0, 1.0);
assert_eq!(quad_free_size(&barely, CENTER), longest_edges(barely), "focal {focal}");
}
}
/// Parallelograms, trapezoids, wild perspective and huge coordinates give a finite, positive size
/// no more than four times the quad's longest edges.
#[test]
fn awkward_quads_get_a_plausible_size() {
let offsets = [-390.0, -120.0, -3.0, 0.0, 0.004, 3.0, 120.0, 390.0];
let mut checked = 0;
for a in offsets {
for b in offsets {
for c in offsets {
for d in offsets {
for scale in [1.0, 1e-2, 1e4] {
let q = [
[(400.0 + a) * scale, 50.0 * scale],
[(1200.0 + b) * scale, 50.0 * scale],
[(1200.0 + c) * scale, (450.0 + d) * scale],
[(400.0 - c) * scale, (450.0 - d) * scale],
];
if !convex_quad(&q) {
continue;
}
checked += 1;
let (w, h) = quad_free_size(&q, CENTER);
let (edge_w, edge_h) = longest_edges(q);
assert!(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0, "{q:?}: {w} x {h}");
assert!(w <= edge_w * 4.0 + 1e-6 && h <= edge_h * 4.0 + 1e-6, "{q:?}: {w} x {h}");
}
}
}
}
}
assert!(checked > 1000, "only {checked} convex quads");
}
+4 -1
View File
@@ -260,7 +260,7 @@ pub fn specs() -> Vec<CommandSpec> {
menu: &[],
shortcut: None,
params: brush_params!(
r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal" → {"damage","offset","aligned","nextSource"}"#
r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal","wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges) → {"damage","offset","aligned","nextSource"}"#
),
enabled: has_pixel_layer,
run: healing_brush,
@@ -397,3 +397,6 @@ pub fn specs() -> Vec<CommandSpec> {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod patch_history_names_tests;
+26 -27
View File
@@ -130,26 +130,19 @@ pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result<Value> {
let from_live = live.is_some();
let map = clone_mapping(s, p, &stroke, CMD)?;
let off = map.offset();
let dmg =
run_stroke(s, "Clone Stamp", id, p, |pre, surf, sel, lock| {
if let Some(l) = live {
*surf = l.surface;
return Ok(l.bounds);
}
if flag(p, "wrap", false) {
let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0);
renderer.push(&stroke.points);
renderer.finish();
let before = surf.clone();
let bounds = renderer.bounds();
return periodic::Composite { target: surf, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection: sel, lock, mode }
.draw(bounds, &stroke.brush, &stroke.points, |r| clone_sample(pre, id, &before, which, r, &map, true, CMD));
}
let (bounds, cov) = coverage(CMD, &stroke)?;
// Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned.
let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?;
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
})?;
let dmg = run_stroke(s, "Clone Stamp", id, p, |pre, surf, sel, lock| {
if let Some(l) = live {
*surf = l.surface;
return Ok(l.bounds);
}
if flag(p, "wrap", false) {
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |before, r| clone_sample(pre, id, before, which, r, &map, true, CMD));
}
let (bounds, cov) = coverage(CMD, &stroke)?;
// Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned.
let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?;
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
})?;
let mut r = clone_result(dmg, off, aligned, p, &stroke);
if from_live {
r["fromLive"] = json!(true);
@@ -272,11 +265,14 @@ impl LiveRetouch {
/// Everything the stroke has touched so far.
pub fn bounds(&self) -> Rect {
let bounds = self.renderer.bounds().union(&self.tail);
if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) {
periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b))
} else {
bounds
}
if self.wraps() { periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b)) } else { bounds }
}
/// Whether the stroke repeats across the canvas edges (View › Pattern Preview). Only the Clone
/// Stamp and the Healing Brush do: the reference application's other retouching tools stop
/// at the edge.
fn wraps(&self) -> bool {
matches!(self.cmd.as_str(), "paint.cloneStamp" | "paint.healingBrush") && flag(&self.params, "wrap", false)
}
/// Every point rendered so far, in order.
@@ -328,7 +324,7 @@ impl LiveRetouch {
let pts: Vec<_> = pts.iter().map(|q| StrokePoint::new(q.x, q.y, q.pressure)).collect();
self.points.extend_from_slice(&pts);
self.renderer.push(&pts);
if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) {
if self.wraps() {
return self.push_periodic();
}
let old = std::mem::replace(&mut self.tail, Rect::EMPTY);
@@ -360,6 +356,8 @@ impl LiveRetouch {
let LivePaint::Clone { which, map, cmd } = &self.paint else {
return Err(bad(&self.cmd, "periodic painting requires a clone source"));
};
let (pre, id, pre_surf, live_cmd) = (&self.pre, self.id, &self.pre_surf, self.cmd.as_str());
let paint = |r| clone_sample(pre, id, pre_surf, *which, r, map, true, cmd);
let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?;
periodic::Composite {
target: surf,
@@ -369,8 +367,9 @@ impl LiveRetouch {
selection: self.sel.as_ref(),
lock: self.lock,
mode: self.mode,
cmd: live_cmd,
}
.draw(dirty, &self.brush, &self.points, |r| clone_sample(&self.pre, self.id, &self.pre_surf, *which, r, map, true, cmd))
.draw(dirty, &self.brush, &self.points, paint)
}
/// Redraw `r` from the pre-stroke pixels with the clone source through coverage `cov`.
@@ -537,6 +537,15 @@ impl LiveDab {
Ok(self)
}
/// Mix the dabs back without the layer's transparency lock, for a tool that erases a locked
/// layer anyway (the Background Eraser). Call it before pushing any points: build the dab with
/// the stroke's points taken out, then [`Self::push`] them (as `live_background_eraser` does),
/// because points pushed before it were already mixed back with the lock.
pub(crate) fn unlocked(mut self) -> Self {
self.lock = false;
self
}
/// Everything the stroke has touched so far.
pub fn bounds(&self) -> Rect {
self.bounds
+18 -2
View File
@@ -1,4 +1,5 @@
use super::clone::{blend_param, clamp_samples, clone_mapping, clone_result, clone_sample};
use super::periodic;
use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers};
use super::{
BlendMode, CompleteParams, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Stroke, Surface, Value, apply_coverage, bad,
@@ -53,15 +54,30 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
let map = clone_mapping(s, p, &stroke, CMD)?;
let off = map.offset();
let dmg = run_stroke(s, "Healing Brush", id, p, |pre, surf, sel, lock| {
// Pattern Preview: source and destination repeat across the canvas edges, so a stroke over
// a seam heals as one patch and goes on wherever it repeats.
let wrap = flag(p, "wrap", false);
let (bounds, cov) = coverage(CMD, &stroke)?;
let (g, cov) = pad_coverage(bounds, &cov, 2);
let fmt = surf.format();
let src = clone_sample(pre, id, surf, which, g, &map, false, CMD)?;
let src = clone_sample(pre, id, surf, which, g, &map, wrap, CMD)?;
// The destination the texture is fitted to: the layer itself, or what the user sees when
// sampling several layers (so healing onto an empty layer matches the composite).
let dst = if which == SampleLayers::Current { Region::read(surf, g) } else { composite_region(pre, id, which, g, fmt) };
let dst = if wrap {
periodic::sample(pre, id, surf, which, g, CMD)?
} else if which == SampleLayers::Current {
Region::read(surf, g)
} else {
composite_region(pre, id, which, g, fmt)
};
let mask: Vec<bool> = cov.iter().map(|c| *c > 0.0).collect();
let healed = heal_region(&fmt, &src, &dst, &mask);
if wrap {
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |_, r| {
let part = healed.crop(r);
if part.rect == r { Ok(part) } else { Err(bad(CMD, "the healed patch does not cover the stroke")) }
});
}
Ok(apply_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode))
})?;
Ok(clone_result(dmg, off, aligned, p, &stroke))
+61 -6
View File
@@ -23,6 +23,8 @@ use super::{
};
const CMD: &str = "paint.patch";
/// The History step of applying a patch, in every mode.
const HISTORY_NAME: &str = "Patch Selection";
/// Largest patch, in pixels of the selection's bounding box. The solve holds the two regions, the
/// result and per-channel float planes of it (on the order of 150 bytes per pixel with four
@@ -151,6 +153,7 @@ struct Plan {
/// Shift of the repaired area from the selection, and of the texture from the repaired area.
dst_shift: (i32, i32),
src_shift: (i32, i32),
/// Destination mode: a hard rectangular selection moves with the patch.
destination: bool,
offset: (i32, i32),
}
@@ -211,16 +214,63 @@ fn patch_surface(surf: &mut Surface, sel: &Surface, plan: &Plan, lock: bool, ste
apply_coverage(surf, g, &cov, 1.0, None, lock, &healed, BlendMode::Normal)
}
/// Rows scanned per band by [`is_hard_rect_within`], so the coverage buffer stays small.
const RECT_BAND_ROWS: i32 = 64;
/// Whether `sel` is a hard-edged rectangle: nothing selected outside its own `bounds` and every pixel
/// inside fully selected (the only Destination selection measured to move with the patch). The
/// bounds may reach past the canvas; the patched area is then only the part on the canvas. Bounds
/// of more than [`MAX_PIXELS`] pixels (the patch's own cap) are never classified as a hard
/// rectangle, so a huge selection moved mostly off the canvas is not scanned and stays in place.
fn is_hard_rect(sel: &Surface, bounds: Rect) -> bool {
is_hard_rect_within(sel, bounds, MAX_PIXELS)
}
/// [`is_hard_rect`] with the pixel `limit` given. Scans `bounds` in bands of [`RECT_BAND_ROWS`] rows
/// and stops at the first pixel that is not fully selected.
fn is_hard_rect_within(sel: &Surface, bounds: Rect, limit: u64) -> bool {
let (w, h) = ((i64::from(bounds.x1) - i64::from(bounds.x0)).max(0) as u64, (i64::from(bounds.y1) - i64::from(bounds.y0)).max(0) as u64);
if w.saturating_mul(h) > limit || sel.default_pixel().first().copied().unwrap_or(0.0) > 0.0 {
return false;
}
let mut y = bounds.y0;
while y < bounds.y1 {
let y1 = y.saturating_add(RECT_BAND_ROWS).min(bounds.y1);
if !coverage(sel, Rect::new(bounds.x0, y, bounds.x1, y1)).iter().all(|c| *c >= 1.0) {
return false;
}
y = y1;
}
true
}
pub(super) fn patch(s: &mut Session, p: &Value) -> Result<Value> {
if flag(p, "contentAware", false) {
return patch_content_aware(s, p);
}
let plan = plan(s, p)?;
let label = if plan.destination { "Patch (Destination)" } else { "Patch" };
let dmg = run_stroke(s, label, plan.id, p, |pre, surf, _, lock| {
let sel = pre.selection.as_ref().ok_or_else(|| bad(CMD, "select the area to patch first"))?;
Ok(patch_surface(surf, sel, &plan, lock, 1))
})?;
let label = HISTORY_NAME;
let dmg = if plan.destination {
// Destination: a plain rectangular selection moves with the patch, in the same history state.
let dmg = s.edit(label, |doc, _| {
let sel = doc.selection.clone().ok_or_else(|| bad(CMD, "select the area to patch first"))?;
let (surf, lock) = crate::channel_cmds::target_surface(doc, plan.id, p)?;
let dmg = patch_surface(surf, &sel, &plan, lock, 1);
let bounds = sel.content_bounds();
if is_hard_rect(&sel, bounds) {
let (dx, dy) = plan.offset;
doc.selection = Some(sel.translated(dx, dy, bounds));
}
Ok(dmg)
})?;
s.hint_damage(dmg);
dmg
} else {
run_stroke(s, label, plan.id, p, |pre, surf, _, lock| {
let sel = pre.selection.as_ref().ok_or_else(|| bad(CMD, "select the area to patch first"))?;
Ok(patch_surface(surf, sel, &plan, lock, 1))
})?
};
Ok(json!({ "damage": damage_json(dmg), "offset": [plan.offset.0, plan.offset.1] }))
}
@@ -263,6 +313,7 @@ fn level(p: &Value, k: &str, default: u8, lo: u8, hi: u8) -> Result<u8> {
/// docs), as a background job.
fn patch_content_aware(s: &mut Session, p: &Value) -> Result<Value> {
use super::content_aware_move::{Target, land, mask, read, window};
// The job's progress text; its History step is `HISTORY_NAME`.
const LABEL: &str = "Patch (Content-Aware)";
let plan = plan(s, p)?;
let structure = level(p, "structure", 4, 1, 7)?;
@@ -294,7 +345,7 @@ fn patch_content_aware(s: &mut Session, p: &Value) -> Result<Value> {
}
},
move |s, (surf, damage)| {
s.edit(LABEL, |doc, _| {
s.edit(HISTORY_NAME, |doc, _| {
*crate::channel_cmds::target_surface(doc, target.id, &p)?.0 = surf;
Ok(())
})?;
@@ -303,3 +354,7 @@ fn patch_content_aware(s: &mut Session, p: &Value) -> Result<Value> {
},
)
}
#[cfg(test)]
#[path = "patch_destination_selection_tests.rs"]
mod patch_destination_selection_tests;
@@ -0,0 +1,203 @@
//! Patch in Destination mode moves a plain rectangular selection with the patch (#12119).
use super::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "depth": 8, "mode": "rgb"})).unwrap();
s.edit("setup", |doc, active| {
let b = doc.bounds();
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
let fmt = surf.format();
let mut data = Vec::new();
for y in b.y0..b.y1 {
for x in b.x0..b.x1 {
let v = if (x / 8 + y / 8) % 2 == 0 { 0.2 } else { 0.8 };
let px = if x >= 400 { [0.1, 0.6, 0.2, 1.0] } else { [v, v, v, 1.0] };
data.extend(photocraft_raster::from_rgba(&fmt, px));
}
}
surf.write_region(b, &data);
Ok(())
})
.unwrap();
s
}
fn bounds(s: &mut Session) -> Value {
s.execute("document.inspect", json!({})).unwrap()["selectionBounds"].clone()
}
fn px(s: &Session, x: i32, y: i32) -> [f32; 4] {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)
}
fn history_len(s: &Session) -> usize {
s.active().unwrap().history.past_len()
}
fn select_rect(s: &mut Session) {
s.execute("select.rect", json!({"x": 120, "y": 120, "width": 40, "height": 40})).unwrap();
}
const DESTINATION: fn() -> Value = || json!({"mode": "destination", "offset": [460, 280]});
#[test]
fn destination_moves_the_selection_with_the_patch_and_undo_restores_both() {
let mut s = session();
select_rect(&mut s);
let before = px(&s, 600, 420);
let source_before: Vec<[f32; 4]> = [(130, 130), (140, 140), (148, 140)].iter().map(|&(x, y)| px(&s, x, y)).collect();
let r = s.execute("paint.patch", DESTINATION()).unwrap();
assert_eq!(r["offset"], json!([460, 280]));
// The damage covers the patched area (the 40 px square at the destination, plus the solve's ring).
assert_eq!(r["damage"], json!([578, 398, 44, 44]));
assert_eq!(bounds(&mut s), json!([580, 400, 40, 40]));
assert_ne!(px(&s, 600, 420), before, "pixels changed too");
// Source pixels untouched.
let source_after: Vec<[f32; 4]> = [(130, 130), (140, 140), (148, 140)].iter().map(|&(x, y)| px(&s, x, y)).collect();
assert_eq!(source_after, source_before);
// The destination carries the source texture: the step between two neighbouring checker cells is kept
// in the same direction and at a similar strength (the seamless clone adds a smooth colour correction, and the
// red channel clamps at 0 on the dark green, so the step shrinks).
let step_src = px(&s, 140, 140)[0] - px(&s, 148, 140)[0];
let step_dst = px(&s, 600, 420)[0] - px(&s, 608, 420)[0];
assert!(step_src * step_dst > 0.0 && step_dst.abs() > 0.2, "texture kept: source step {step_src}, destination step {step_dst}");
// The moved selection is still a hard-edged rectangle exactly filling its bounds.
let d = s.active().unwrap();
let sel = d.doc.selection.as_ref().unwrap();
assert!(is_hard_rect(sel, sel.content_bounds()));
// One history state: a single undo brings back the pixels and the old selection.
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(bounds(&mut s), json!([120, 120, 40, 40]));
assert_eq!(px(&s, 600, 420), before);
}
#[test]
fn destination_selection_stays_when_it_is_not_a_plain_rectangle() {
let cases: [(&str, Value, Value); 4] = [
("feathered", json!({"x": 120, "y": 120, "width": 40, "height": 40, "feather": 6.0}), json!(null)),
("ellipse", json!({"x": 120, "y": 120, "width": 40, "height": 40, "ellipse": true}), json!(null)),
("lasso", json!({"points": [[120, 120], [160, 130], [140, 165]]}), json!("lasso")),
("rectangle with a hole", json!({"x": 120, "y": 120, "width": 40, "height": 40}), json!("hole")),
];
for (name, params, kind) in cases {
let mut s = session();
let cmd = if kind == json!("lasso") { "select.lasso" } else { "select.rect" };
s.execute(cmd, params).unwrap();
if kind == json!("hole") {
// Same bounds as the rectangle, but not every pixel inside is fully selected.
s.execute("select.rect", json!({"x": 135, "y": 135, "width": 10, "height": 10, "mode": "subtract"})).unwrap();
}
let sel_before = bounds(&mut s);
let area = |s: &Session| -> Vec<[f32; 4]> { (400..440).flat_map(|y| (580..620).map(move |x| (x, y))).map(|(x, y)| px(s, x, y)).collect() };
let before = area(&s);
s.execute("paint.patch", DESTINATION()).unwrap();
assert_eq!(bounds(&mut s), sel_before, "{name}: the selection stays in place");
assert_ne!(area(&s), before, "{name}: the patch still lands");
}
}
#[test]
fn partial_coverage_and_oversized_rectangles_are_not_constructible_apart_from_the_hole_case() {
// `plan.area` is the selection's own content bounds, so a rectangle larger than the area cannot
// exist, and the area is never wider than the selection. The only way the bounds equal the area
// yet coverage falls short is a hole (covered above). An inverted selection makes the area the
// whole canvas, which no non-zero drag can keep on the canvas, so Patch refuses it.
let mut s = session();
select_rect(&mut s);
s.execute("select.inverse", json!({})).unwrap();
assert!(s.execute("paint.patch", DESTINATION()).is_err());
}
#[test]
fn destination_without_a_selection_fails_and_leaves_history_alone() {
let mut s = session();
// A marker step after the setup, so a stray undo would be visible.
s.edit("marker", |doc, active| {
doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 20, 20), &[1.0, 0.0, 0.0, 1.0]);
Ok(())
})
.unwrap();
let h = history_len(&s);
assert!(s.execute("paint.patch", DESTINATION()).is_err());
assert_eq!(history_len(&s), h, "no history entry");
// Undo reverts the marker (the last real step), not the setup.
s.execute("edit.undo", json!({})).unwrap();
assert_ne!(px(&s, 15, 15), [1.0, 0.0, 0.0, 1.0], "the marker step was undone");
assert!((px(&s, 450, 300)[0] - 0.1).abs() < 0.01 && (px(&s, 450, 300)[1] - 0.6).abs() < 0.01, "the setup step is still there");
}
#[test]
fn redo_restores_the_patched_pixels_and_the_moved_selection() {
let mut s = session();
select_rect(&mut s);
let before = px(&s, 600, 420);
s.execute("paint.patch", DESTINATION()).unwrap();
let patched = px(&s, 600, 420);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(bounds(&mut s), json!([120, 120, 40, 40]));
assert_eq!(px(&s, 600, 420), before);
s.execute("edit.redo", json!({})).unwrap();
assert_eq!(bounds(&mut s), json!([580, 400, 40, 40]));
assert_eq!(px(&s, 600, 420), patched);
}
#[test]
fn source_mode_keeps_the_selection() {
let mut s = session();
select_rect(&mut s);
s.execute("paint.patch", json!({"offset": [260, 0]})).unwrap();
assert_eq!(bounds(&mut s), json!([120, 120, 40, 40]));
}
#[test]
fn content_aware_keeps_the_selection_and_changes_the_pixels() {
let mut s = session();
select_rect(&mut s);
// Content-Aware ignores the mode and fills the selection itself from the dragged-to place (the
// green half), so the pixels under the selection change.
let before = px(&s, 140, 140);
s.execute("paint.patch", json!({"offset": [400, 0], "contentAware": true})).unwrap();
assert_eq!(bounds(&mut s), json!([120, 120, 40, 40]));
assert_ne!(px(&s, 140, 140), before, "the selected area was filled");
}
#[test]
fn destination_moves_a_hard_rectangle_that_extends_past_the_canvas() {
let mut s = session();
// 60x40 rectangle with 20 columns off the left edge; the part on the canvas is x 0..40.
s.execute("select.rect", json!({"x": 0, "y": 100, "width": 60, "height": 40})).unwrap();
s.execute("select.transformSelection", json!({"dx": -20, "dy": 0})).unwrap();
let sel_before = bounds(&mut s);
let before = px(&s, 480, 400);
s.execute("paint.patch", DESTINATION()).unwrap();
assert_ne!(px(&s, 480, 400), before, "the patch lands on the canvas part");
let d = s.active().unwrap();
let sel = d.doc.selection.as_ref().unwrap();
assert_eq!(sel.content_bounds(), Rect::new(440, 380, 500, 420), "the whole rectangle moved, off-canvas part included");
assert!(sel.read_region(Rect::new(440, 380, 500, 420)).chunks_exact(sel.channels().max(1)).all(|p| p[0] >= 1.0));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(bounds(&mut s), sel_before);
assert_eq!(px(&s, 480, 400), before);
}
#[test]
fn hard_rect_check_is_capped_and_scans_every_band() {
let mut s = session();
// 40x150 rectangle: three bands of 64 rows (64 + 64 + 22).
s.execute("select.rect", json!({"x": 100, "y": 100, "width": 40, "height": 150})).unwrap();
let d = s.active().unwrap();
let sel = d.doc.selection.as_ref().unwrap();
let b = sel.content_bounds();
assert_eq!(b, Rect::new(100, 100, 140, 250));
assert!(!is_hard_rect_within(sel, b, 5999), "over the limit is never a hard rectangle");
assert!(is_hard_rect_within(sel, b, 6000), "at the limit it is checked as usual");
assert!(is_hard_rect_within(sel, b, u64::MAX));
// A hole in the third band must still be found.
let mut holed = sel.clone();
let fmt = holed.format();
holed.write_region(Rect::new(120, 240, 121, 241), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 0.0, 0.0]));
assert!(!is_hard_rect_within(&holed, b, u64::MAX), "a hole past the first band fails the check");
}
@@ -0,0 +1,100 @@
//! History step names of the Patch Tool (#12117): "Patch Tool" for the lasso it draws with and
//! "Patch Selection" for applying a patch in every mode; the plain Lasso tool keeps "Lasso".
use super::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 128, "height": 64, "depth": 8, "mode": "rgb"})).unwrap();
s
}
fn last_step(s: &Session) -> Option<String> {
s.active().unwrap().history.undo_label().map(str::to_string)
}
#[test]
fn applying_a_patch_is_one_step_named_patch_selection_in_every_mode() {
let modes = [
json!({"offset": [30, 0]}),
json!({"offset": [30, 0], "mode": "source"}),
json!({"offset": [30, 0], "mode": "destination"}),
json!({"offset": [30, 0], "contentAware": true}),
json!({"offset": [30, 0], "mode": "destination", "contentAware": true}),
];
for p in modes {
let mut s = session();
s.execute("select.rect", json!({"x": 16, "y": 22, "width": 20, "height": 20})).unwrap();
let steps = s.active().unwrap().history.past_len();
s.execute("paint.patch", p.clone()).unwrap();
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{p}: one step");
assert_eq!(last_step(&s).as_deref(), Some("Patch Selection"), "{p}");
}
}
const TRIANGLE: [[i32; 2]; 3] = [[16, 22], [36, 22], [16, 42]];
#[test]
fn the_lasso_is_named_for_the_tool_that_drew_it() {
let mut s = session();
s.execute("select.lasso", json!({"points": TRIANGLE})).unwrap();
assert_eq!(last_step(&s).as_deref(), Some("Lasso"), "the Lasso tool sends no name");
for mode in ["replace", "add", "subtract", "intersect"] {
s.execute("select.lasso", json!({"points": TRIANGLE, "mode": mode, "historyName": "Patch Tool"})).unwrap();
assert_eq!(last_step(&s).as_deref(), Some("Patch Tool"), "{mode}");
}
s.execute("select.lasso", json!({"points": TRIANGLE, "polygonal": true, "historyName": "Patch Tool"})).unwrap();
assert_eq!(last_step(&s).as_deref(), Some("Polygonal Lasso"), "the Polygonal Lasso keeps its own name");
}
#[test]
fn a_hostile_history_name_is_refused_without_a_step() {
let mut s = session();
let steps = s.active().unwrap().history.past_len();
let invisible = ["\u{200B}", " \u{200B}\u{FEFF} ", "\u{3164}", "\u{FE0F}", "\u{E0020}", "\u{00AD}", "\u{2800}"];
let hidden = ["Patch\u{202E}looT", "\u{FEFF}Patch Tool", "Patch Tool\u{200B}", "\u{2066}Patch", "Patch\u{2028}Tool", "a\u{2029}b"];
let ends = ["Patch Tool\n", "\r\nPatch Tool", "\tPatch", "\u{0085}Patch", "Patch\u{2028}"];
let others = [json!(""), json!(" "), json!("x".repeat(65)), json!("a\nb"), json!(7), json!(["Patch Tool"])];
let others = ends.iter().map(|n| json!(n)).chain(others);
for name in invisible.iter().chain(&hidden).map(|n| json!(n)).chain(others) {
assert!(s.execute("select.lasso", json!({"points": TRIANGLE, "historyName": name})).is_err(), "{name}");
let polygonal = json!({"points": TRIANGLE, "polygonal": true, "historyName": name});
assert!(s.execute("select.lasso", polygonal).is_err(), "polygonal {name}");
}
assert_eq!(s.active().unwrap().history.past_len(), steps);
}
#[test]
fn a_name_joining_its_letters_with_a_zero_width_joiner_is_kept() {
let mut s = session();
for name in ["\u{0645}\u{200C}\u{06CC}", "\u{1F469}\u{200D}\u{1F4BB}", "Patch Tool \u{2713}"] {
s.execute("select.lasso", json!({"points": TRIANGLE, "historyName": name})).unwrap();
assert_eq!(last_step(&s).as_deref(), Some(name));
}
}
#[test]
fn spaces_and_joiners_at_the_ends_are_trimmed_and_only_what_is_left_counts() {
let mut s = session();
let padded = format!("{}{}", " ".repeat(10), "x".repeat(60));
let joined = format!("Patch Tool{}", "\u{200D}".repeat(60));
let cases = [
("Patch Tool\u{200D}", "Patch Tool"),
(" \u{200C}Patch Tool ", "Patch Tool"),
("Love \u{2764}\u{FE0F}", "Love \u{2764}\u{FE0F}"),
(joined.as_str(), "Patch Tool"),
("Patch Tool\u{2800}", "Patch Tool"),
("\u{3164}\u{2800}Patch Tool\u{FFA0} \u{115F}", "Patch Tool"),
("Patch Tool\u{2065}\u{FFF0}", "Patch Tool"),
("\u{17B4}Patch Tool", "Patch Tool"),
("Patch Tool \u{FE0F}", "Patch Tool"),
("\u{FE0F}Patch Tool", "Patch Tool"),
("Patch \u{2764}\u{FE0F}\u{2800}", "Patch \u{2764}\u{FE0F}"),
("Patch \u{1100}\u{1160}", "Patch \u{1100}\u{1160}"),
("\u{115F}\u{1161} Patch", "\u{115F}\u{1161} Patch"),
];
for (name, stored) in cases.iter().copied().chain([(padded.as_str(), &padded[10..])]) {
s.execute("select.lasso", json!({"points": TRIANGLE, "historyName": name})).unwrap();
assert_eq!(last_step(&s).as_deref(), Some(stored), "{name:?}");
}
}
+31 -2
View File
@@ -1,6 +1,6 @@
//! Bounded reads from the repeating document tile used by Pattern Preview.
use super::{BlendMode, BrushSettings, Document, LayerId, Rect, Region, Result, SampleLayers, StrokePoint, Surface, alpha_index, apply_coverage, bad};
use super::{BlendMode, BrushSettings, Document, LayerId, Rect, Region, Result, SampleLayers, Stroke, StrokePoint, Surface, alpha_index, apply_coverage, bad};
/// At most four disjoint rectangles in the document tile. Projecting the dirty area separately
/// from the stroke bounds avoids scanning the whole document when a small dab crosses a seam.
@@ -23,6 +23,33 @@ pub(super) fn project(rect: Rect, tile: Rect) -> Vec<Rect> {
ys.into_iter().flat_map(|(y0, y1)| xs.iter().map(move |&(x0, x1)| Rect::new(x0, y0, x1, y1))).collect()
}
/// A composite tool's stroke wrapped around the document: `paint` gives the pixels for a
/// rectangle in the stroke's own coordinates, from the target as it was before the stroke, and
/// they go on through the stroke's coverage wherever it repeats on the document.
#[allow(clippy::too_many_arguments)]
pub(super) fn stroke(
pre: &Document,
target: &mut Surface,
stroke: &Stroke,
selection: Option<&Surface>,
lock: bool,
mode: BlendMode,
cmd: &str,
mut paint: impl FnMut(&Surface, Rect) -> Result<Region>,
) -> Result<Rect> {
let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0);
renderer.push(&stroke.points);
renderer.finish();
let before = target.clone();
let bounds = renderer.bounds();
Composite { target, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection, lock, mode, cmd }.draw(
bounds,
&stroke.brush,
&stroke.points,
|r| paint(&before, r),
)
}
/// Composite periodic copies of one stroke, restoring each dirty patch from pre-stroke pixels.
/// Each dab wraps once, then builds flow towards its opacity ceiling. Stroke opacity and
/// selection are applied once after all dabs, including repeated visits through other tiles.
@@ -34,6 +61,8 @@ pub(super) struct Composite<'a> {
pub selection: Option<&'a Surface>,
pub lock: bool,
pub mode: BlendMode,
/// The command an over-budget stroke's error names.
pub cmd: &'a str,
}
impl Composite<'_> {
@@ -138,7 +167,7 @@ impl Composite<'_> {
);
*work = work.saturating_add(r.width() as u64 * r.height() as u64);
if *work > 64 * 1024 * 1024 {
return Err(bad("paint.cloneStamp", "wrapped stroke exceeds its coverage budget"));
return Err(bad(self.cmd, "wrapped stroke exceeds its coverage budget"));
}
ctx.rasterize_into(dab, dual, r, &mut values, wet.then_some(&mut depths));
let mut sampled = None;
+190 -1
View File
@@ -1022,7 +1022,7 @@ fn patch_content_aware_copies_the_dragged_to_content_into_the_selection() {
let (got, want) = (rgba(&s, x, y), texture(x, y));
assert!((got[0] - want[0]).abs() <= tol(depth), "depth {depth}: untouched {x},{y}: {got:?}");
}
assert_eq!(s.active().unwrap().history.undo_label(), Some("Patch (Content-Aware)"));
assert_eq!(s.active().unwrap().history.undo_label(), Some("Patch Selection"));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(rgba(&s, 44, 24)[1], 0.0, "depth {depth}: undo brings the blemish back");
}
@@ -2532,3 +2532,192 @@ fn periodic_clone_interior_matches_ordinary_brush_masks_and_transparency() {
}
}
}
// ---------------------------------------------------------------------------------------------
// View › Pattern Preview: Clone Stamp and Healing Brush wrap across the canvas edges (#8883)
// ---------------------------------------------------------------------------------------------
/// The canvas the Pattern Preview tests wrap around.
const WRAP: (u32, u32) = (48, 36);
/// `texture` repeated every canvas, so each copy of a pixel holds the same colour.
fn tiled_texture(x: i32, y: i32) -> [f32; 4] {
texture(x.rem_euclid(WRAP.0 as i32), y.rem_euclid(WRAP.1 as i32))
}
/// A stroke from just inside the corner where the middle copy of a three-by-three tiling meets
/// the next copies, out across both of its edges.
fn corner_stroke(extra: &Value) -> Value {
let mut p = json!({"points": [[84, 64], [106, 79]], "size": 12, "hardness": 100});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
p
}
/// The stroke tools that wrap, with their options. Both composite a paint image through the
/// stroke's coverage (`periodic::Composite`), which matches the ordinary composite only within
/// rounding.
fn wrap_cases() -> [(&'static str, Value); 2] {
[("paint.healingBrush", json!({"offset": [-20, -14]})), ("paint.cloneStamp", json!({"offset": [-20, -14]}))]
}
/// The native-channel difference `periodic::Composite` may leave against the ordinary composite.
fn composite_tolerance(depth: u64) -> f32 {
match depth {
8 => 1.1 / 255.0,
16 => 1.1 / 65535.0,
_ => 0.00001,
}
}
#[test]
fn every_wrapping_stroke_paints_the_canvas_as_on_the_canvas_tiled_three_by_three() {
// A stroke with `"wrap": true` gives each pixel of the canvas what the same stroke gives the
// copy of that pixel it goes over, on a document holding the canvas tiled three by three.
let (w, h) = (WRAP.0 as usize, WRAP.1 as usize);
for depth in DEPTHS {
for (cmd, extra) in wrap_cases() {
let mut canvas = session(WRAP.0, WRAP.1, depth, "rgb");
paint_layer(&mut canvas, tiled_texture);
let mut tiled = session(3 * WRAP.0, 3 * WRAP.1, depth, "rgb");
paint_layer(&mut tiled, tiled_texture);
let (mut wrapped, plain) = (corner_stroke(&extra), corner_stroke(&extra));
wrapped["wrap"] = json!(true);
canvas.execute(cmd, wrapped).unwrap_or_else(|e| panic!("{cmd} at {depth}: {e}"));
let before = layer_pixels(&tiled);
tiled.execute(cmd, plain).unwrap();
let (got, want) = (layer_pixels(&canvas), layer_pixels(&tiled));
let n = got.len() / (w * h);
let at = |x: usize, y: usize| (y * 3 * w + x) * n..(y * 3 * w + x + 1) * n;
let tolerance = composite_tolerance(depth);
let (mut moved, mut edges) = (0, [false; 4]);
for y in 0..h {
for x in 0..w {
let copies = (0..3).flat_map(|j| (0..3).map(move |i| (x + i * w, y + j * h)));
let changed: Vec<_> = copies.filter(|&(u, v)| want[at(u, v)] != before[at(u, v)]).collect();
let (pixel, expected) = match changed.as_slice() {
[] => (&got[(y * w + x) * n..][..n], &before[at(x, y)]),
[(u, v)] => (&got[(y * w + x) * n..][..n], &want[at(*u, *v)]),
_ => panic!("{cmd}: ({x}, {y}) has two copies under the stroke"),
};
let error = pixel.iter().zip(expected).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(error <= tolerance, "{cmd} {extra} at {depth}-bit: ({x}, {y}) is off by {error}");
if !changed.is_empty() {
moved += 1;
edges[0] |= x < 8;
edges[1] |= x >= w - 8;
edges[2] |= y < 8;
edges[3] |= y >= h - 8;
}
}
}
assert!(moved > 150 && edges.iter().all(|&e| e), "{cmd} {extra} at {depth}-bit: the stroke crossed both edges ({moved} px, {edges:?})");
}
}
}
#[test]
fn a_wrapped_stroke_inside_the_canvas_paints_as_an_ordinary_one() {
let p = json!({"points": [[130, 110], [150, 118], [168, 112]], "size": 14, "hardness": 60});
for depth in [8, 32] {
for (cmd, extra) in wrap_cases() {
let run = |wrap: bool| {
let mut s = session(300, 230, depth, "rgb");
paint_layer(&mut s, tiled_texture);
let mut q = p.clone();
for (k, v) in extra.as_object().unwrap() {
q[k] = v.clone();
}
q["wrap"] = json!(wrap);
s.execute(cmd, q).unwrap();
layer_pixels(&s)
};
let (plain, wrapped) = (run(false), run(true));
let error = plain.iter().zip(&wrapped).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
assert!(error <= composite_tolerance(depth), "{cmd} {extra} at {depth}-bit: off by {error}");
}
}
}
#[test]
fn a_wrapped_dab_bigger_than_the_canvas_stays_on_it() {
for (cmd, extra) in wrap_cases() {
let mut s = session(16, 12, 8, "rgb");
paint_layer(&mut s, tiled_texture);
let before = layer_pixels(&s);
let mut p = json!({"points": [[8, 6], [30, 20]], "size": 60, "hardness": 0, "wrap": true});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let r = s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
let d = r["damage"].as_array().map(|d| d.iter().filter_map(Value::as_i64).collect::<Vec<_>>()).unwrap_or_default();
assert!(matches!(d.as_slice(), [x, y, w, h] if *x >= 0 && *y >= 0 && x + w <= 16 && y + h <= 12), "{cmd}: damage {d:?} is on the canvas");
let st = s.active().unwrap();
let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
assert!([(-1, 5), (16, 5), (5, -1), (5, 12), (40, 30)].iter().all(|&(x, y)| surf.rgba(x, y)[3] == 0.0), "{cmd}: nothing lands off the canvas");
assert!(layer_pixels(&s) != before, "{cmd} {extra}: the stroke changed the canvas");
}
}
#[test]
fn the_tools_the_reference_application_does_not_wrap_stop_at_the_canvas_edge() {
// Measured in the reference application: in Pattern Preview the Clone Stamp and Healing
// Brush carry a stroke on across the canvas edges, but Blur … Sponge, Color Replacement,
// Background Eraser, Pattern Stamp and History Brush warn that they don't wrap, and Spot
// Healing stops at the edge too. Their `wrap` stroke over the corner paints as the same
// stroke without it.
let points = [[36.0, 24.0], [58.0, 39.0]];
let cases = [
("paint.blur", json!({"strength": 80})),
("paint.sharpen", json!({"strength": 60})),
("paint.smudge", json!({"strength": 70})),
("paint.dodge", json!({"exposure": 60})),
("paint.burn", json!({"exposure": 40})),
("paint.sponge", json!({"mode": "saturate"})),
("paint.colorReplacement", json!({"color": "#ff8000", "tolerance": 60})),
("paint.backgroundEraser", json!({"tolerance": 40})),
("paint.patternStamp", json!({"pattern": "Checkerboard"})),
("paint.patternStamp", json!({"pattern": "Bricks", "impressionist": true, "seed": 7})),
("paint.historyBrush", json!({"state": 1})),
("paint.spotHealing", json!({"type": "contentAware"})),
];
for (cmd, extra) in cases {
let run = |wrap: bool| {
let mut s = session(WRAP.0, WRAP.1, 8, "rgb");
paint_layer(&mut s, tiled_texture);
// Painted over since history state 1, so the History Brush has something to bring back.
paint_layer(&mut s, |x, y| tiled_texture(x + 7, y + 5));
let mut p = dab_opts(&points, 100, &extra);
p["size"] = json!(12);
p["wrap"] = json!(wrap);
let before = layer_pixels(&s);
s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}"));
(before, layer_pixels(&s))
};
let ((before, plain), (_, wrapped)) = (run(false), run(true));
assert!(plain != before, "{cmd} {extra}: the stroke paints inside the canvas");
assert!(wrapped == plain, "{cmd} {extra}: nothing comes back at the opposite edges");
}
}
#[test]
fn live_history_and_pattern_strokes_stop_at_the_canvas_edge() {
// The History Brush and aligned Pattern Stamp previews stop at the edge as their commits do.
let points = [[36.0, 24.0], [58.0, 39.0]];
let pts: Vec<_> = points.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect();
for (cmd, extra) in [("paint.historyBrush", json!({"state": 1})), ("paint.patternStamp", json!({"pattern": "Checkerboard"}))] {
let bounds = |wrap: bool| {
let mut s = session(WRAP.0, WRAP.1, 8, "rgb");
paint_layer(&mut s, tiled_texture);
paint_layer(&mut s, |_, _| [0.15, 0.2, 0.7, 1.0]);
let mut p = dab_opts(&points[..1], 100, &extra);
p["size"] = json!(12);
p["wrap"] = json!(wrap);
let mut live = LiveRetouch::begin(&s, cmd, &p).unwrap();
live.push(&pts[1..]).unwrap();
live.bounds()
};
assert_eq!(bounds(true), bounds(false), "{cmd}: the live stroke stays where it was drawn");
}
}
+35 -4
View File
@@ -17,6 +17,8 @@ mod modify_window;
mod color_range_performance;
#[cfg(test)]
mod color_range_window_tests;
#[cfg(test)]
mod wand_seed_outside_tests;
fn has_doc(s: &Session) -> std::result::Result<(), String> {
s.active().map(|_| ()).ok_or_else(|| "no document open".into())
@@ -139,9 +141,15 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
Some(plane) => plane,
None => sample_rgba8(s, b(p, "sampleAllLayers", false))?,
};
let region = sel::wand_region(&img, area, (x, y), f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true));
drop(img);
let m = mode(p);
// Subtract and Intersect grow the region from the seed through the selection only (#11779).
// A global match (Contiguous off) ignores the limit, so it skips the full-area mask.
let contiguous = b(p, "contiguous", true);
let within = (contiguous && matches!(m, SelectionMode::Subtract | SelectionMode::Intersect))
.then(|| s.active().and_then(|st| st.doc.selection.as_ref()).map(|sel| sel::mask_from_surface(Some(sel), area)))
.flatten();
let region = sel::wand_region_within(&img, area, (x, y), f(p, "tolerance", 32.0), contiguous, b(p, "antiAlias", true), within.as_deref());
drop(img);
let selected = s.edit("Magic Wand", |doc, _| {
doc.selection = sel::combine_region(doc.selection.as_ref(), region.as_ref(), m);
Ok(doc.selection.is_some())
@@ -622,10 +630,33 @@ fn lasso(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::BadParams { cmd: "select.lasso".into(), msg: "needs at least 3 points".into() });
}
// The History step is named after the tool: the Polygonal Lasso sends `polygonal` (Photoshop).
let step = if b(p, "polygonal", false) { "Polygonal Lasso" } else { "Lasso" };
// The Patch and Content-Aware Move tools draw with this command and send their own name as
// `historyName`, so the plain Lasso tool keeps "Lasso".
// A bad name is refused even when `polygonal` picks the step's name.
let named = match p.get("historyName") {
None | Some(Value::Null) => None,
Some(Value::String(n)) if history_name(n).is_some() => history_name(n),
Some(_) => {
let msg = "historyName must be 1-64 characters with a visible one, and no control, line-break or hidden format characters";
return Err(EngineError::BadParams { cmd: "select.lasso".into(), msg: msg.into() });
}
};
let step = if b(p, "polygonal", false) { "Polygonal Lasso" } else { named.unwrap_or("Lasso") };
polygon_selection(s, "select.lasso", step, &pts, p)
}
/// The History step name for `historyName` `n`: refused when it has a control or line-break
/// character anywhere; otherwise without its invisible end padding (see
/// [`photocraft_plugins::manifest::trim_name`]), so a name that looks like "Patch Tool" is "Patch Tool",
/// and then held to the plug-in menu-label rule.
fn history_name(n: &str) -> Option<&str> {
if n.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')) {
return None;
}
let t = photocraft_plugins::manifest::trim_name(n);
photocraft_plugins::manifest::printable_name(t).then_some(t)
}
/// Selects the polygon `pts` with the lasso tools' `mode`, `antiAlias` and `feather` params, as
/// one history step called `label`.
pub(crate) fn polygon_selection(s: &mut Session, cmd: &str, label: &str, pts: &[(f32, f32)], p: &Value) -> Result<Value> {
@@ -756,7 +787,7 @@ pub fn specs() -> Vec<CommandSpec> {
"select.lasso",
"Lasso",
[],
r##"{"points":[[x,y],…],"mode":"replace|add|subtract|intersect"="replace","antiAlias":bool=true,"feather":px=0,"polygonal":bool=false}"##,
r##"{"points":[[x,y],…],"mode":"replace|add|subtract|intersect"="replace","antiAlias":bool=true,"feather":px=0,"polygonal":bool=false,"historyName"?:text (1..64 characters with a visible one, no control, line-break or hidden format characters, invisible padding at the ends (spaces, joiners, fillers, blank Braille and other default-ignorable blanks, and selectors cut off by them) trimmed; the History step name when a tool other than the Lasso draws it, e.g. "Patch Tool"; default "Lasso")}"##,
has_doc,
lasso
),
@@ -0,0 +1,113 @@
//! #11779: with Contiguous on, the Magic Wand's Subtract and Intersect grow the region from the
//! seed through the current selection only. A seed outside the selection subtracts nothing and
//! intersects to nothing.
use serde_json::json;
use crate::Session;
/// 800 × 600, white, with a grey ramp of ten 40 px blocks from x 100 (100, 105, …, 145).
fn ramp() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
for k in 0..10 {
let v = 100 + 5 * k;
s.execute("select.rect", json!({"x": 100 + 40 * k, "y": 350, "width": 40, "height": 100})).unwrap();
s.execute("edit.fill", json!({"color": format!("#{v:02x}{v:02x}{v:02x}")})).unwrap();
}
s.execute("select.deselect", json!({})).unwrap();
s
}
fn wand(s: &mut Session, x: i32, tolerance: f64, mode: &str) {
s.execute("select.magicWand", json!({"x": x, "y": 400, "tolerance": tolerance, "mode": mode})).unwrap();
}
fn wand_global(s: &mut Session, x: i32, tolerance: f64, mode: &str) {
s.execute("select.magicWand", json!({"x": x, "y": 400, "tolerance": tolerance, "mode": mode, "contiguous": false})).unwrap();
}
/// The columns of row 400 that are at least half selected: (first, end), or `None`. Every
/// column in between must be selected too, so a hole in the run fails the test.
fn selected(s: &Session) -> Option<(i32, i32)> {
let doc = &s.active().unwrap().doc;
let row = photocraft_geom::Rect::new(0, 400, 800, 401);
let m = photocraft_algo::selection::mask_from_surface(doc.selection.as_ref(), row);
let first = m.iter().position(|v| *v >= 0.5)?;
let last = m.iter().rposition(|v| *v >= 0.5)?;
assert!(m[first..=last].iter().all(|v| *v >= 0.5), "a hole in the selected run {first}..={last}");
Some((first as i32, last as i32 + 1))
}
/// Greys 100 to 130 (x 100–380) selected, as tolerance 32 on the first block selects them, plus
/// the Anti-alias fringe: column 380 of grey 135 at about 251/255, as measured in #11776.
fn ramp_selected() -> Session {
let mut s = ramp();
wand(&mut s, 110, 32.0, "replace");
assert_eq!(selected(&s), Some((100, 381)));
s
}
#[test]
fn a_seed_outside_the_selection_subtracts_nothing() {
let mut s = ramp_selected();
// Grey 145 (x 460–500) is outside the selection, though its own region reaches into it.
wand(&mut s, 480, 32.0, "subtract");
assert_eq!(selected(&s), Some((100, 381)), "unchanged");
}
#[test]
fn a_seed_outside_the_selection_intersects_to_nothing() {
let mut s = ramp_selected();
wand(&mut s, 480, 32.0, "intersect");
assert_eq!(selected(&s), None);
}
#[test]
fn a_seed_inside_the_selection_works_as_before() {
// Grey 125 with tolerance 10 reaches greys 115–135; inside the selection that is x 220–380.
// With the default Anti-alias fringe, as measured in #11779: Subtract leaves 100–219 (x 219
// keeps about 6/255, under the 0.5 cut) and Intersect 219–381.
let mut s = ramp_selected();
wand(&mut s, 320, 10.0, "subtract");
assert_eq!(selected(&s), Some((100, 219)));
let mut s = ramp_selected();
wand(&mut s, 320, 10.0, "intersect");
assert_eq!(selected(&s), Some((219, 381)));
}
#[test]
fn contiguous_off_keeps_the_global_match() {
// Without Contiguous the seed's colour matches everywhere, as before: greys 115–145 are
// x 220–500, wherever the seed lies.
let mut s = ramp_selected();
wand_global(&mut s, 480, 32.0, "subtract");
assert_eq!(selected(&s), Some((100, 219)));
let mut s = ramp_selected();
wand_global(&mut s, 480, 32.0, "intersect");
assert_eq!(selected(&s), Some((219, 381)));
}
#[test]
fn without_a_selection_subtract_and_intersect_select_nothing() {
for mode in ["subtract", "intersect"] {
let mut s = ramp();
wand(&mut s, 320, 10.0, mode);
assert_eq!(selected(&s), None, "{mode}");
}
}
#[test]
fn the_fill_passes_only_pixels_at_least_half_selected() {
use photocraft_algo::selection::wand_region_within;
use photocraft_geom::Rect;
// One flat grey row of four pixels; only the coverage limit decides the region.
let img = [[128u8, 128, 128, 255]; 4];
let area = Rect::new(0, 0, 4, 1);
let fill = |within: [f32; 4], seed: i32| wand_region_within(&img, area, (seed, 0), 0.0, true, false, Some(&within));
assert!(fill([0.49, 1.0, 1.0, 1.0], 0).is_none(), "a seed just under half selected finds nothing");
let r = fill([0.5, 1.0, 1.0, 1.0], 0).unwrap();
assert_eq!((0..4).map(|x| r.at(x, 0) >= 0.5).collect::<Vec<_>>(), [true; 4], "half selected counts");
let r = fill([1.0, 1.0, 0.49, 1.0], 0).unwrap();
assert_eq!((0..4).map(|x| r.at(x, 0) >= 0.5).collect::<Vec<_>>(), [true, true, false, false], "the fill stops at 0.49");
}
@@ -223,24 +223,24 @@ fn bad_layers_params_are_errors_not_panics() {
}
#[test]
fn straighten_layer_rotates_every_selected_layer() {
// Photoshop's Straighten Layer turns all the selected layers, not just the active one; it
// goes through `edit.transform` without a layer, so it takes the selection like Free Transform.
fn straighten_layer_wants_one_selected_layer() {
// #12033: the reference greys Straighten Layer out while two layers are selected, so it no
// longer turns the whole selection the way Free Transform does
// (`free_transform_moves_every_selected_layer_in_one_step` covers that).
let (mut s, paint, text) = two_layers();
let (p0, m0) = (bounds(&s, paint), text_matrix(&s, text));
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
let steps = s.active().unwrap().history.past_len();
let r = s.execute("image.analysis.straightenLayer", json!({})).unwrap();
assert_eq!(r["cropped"], false);
assert!(bounds(&s, paint) != p0, "the selected pixel layer turned too");
assert!(text_matrix(&s, text)[1].abs() > 0.05 && m0[1].abs() < 1e-9, "the active type layer turned");
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one history step");
assert!(s.undo());
assert_eq!((bounds(&s, paint), text_matrix(&s, text)), (p0, m0), "and one Undo takes both back");
assert_eq!(s.active().unwrap().selected_layers().len(), 2, "both selected, the type layer active");
assert!(!s.is_enabled("image.analysis.straightenLayer"), "two selected layers");
assert!(s.execute("image.analysis.straightenLayer", json!({})).is_err());
assert_eq!((bounds(&s, paint), text_matrix(&s, text)), (p0, m0), "nothing turned");
assert_eq!(s.active().unwrap().history.past_len(), steps, "and no history step");
// With one layer selected, only that layer turns.
s.execute("layer.select", json!({"layer": paint.0})).unwrap();
s.execute("image.analysis.rulerTool", json!({"start": [10, 30], "end": [70, 25]})).unwrap();
assert!(s.is_enabled("image.analysis.straightenLayer"), "a single layer");
s.execute("image.analysis.straightenLayer", json!({})).unwrap();
assert!(bounds(&s, paint) != p0);
assert_eq!(text_matrix(&s, text), m0, "an unselected layer stays put");
+52 -2
View File
@@ -8,7 +8,7 @@
use std::sync::Arc;
use photocraft_color::{Color, PixelFormat};
use photocraft_color::{Color, ColorMode, PixelFormat};
use photocraft_doc::text::{
AntiAlias, Caps, CharStyle, FontBaseline, FontFeature, FontVariation, Kerning, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection,
TextRun, TextShape,
@@ -937,6 +937,56 @@ pub(crate) fn new_text_layer(s: &Session, p: &Value, cmd: &str) -> Result<TextLa
Ok(t)
}
/// The name of the history state a new type layer makes: what `type.create` records, and what the
/// Type tool's commit keeps in the modes [`commits_as_selection`] names (#12041).
pub const NEW_TYPE_LAYER_LABEL: &str = "New Type Layer";
/// Whether committing Type-tool text `t` in colour mode `mode` leaves no type layer, but a
/// selection in the shape of its glyphs, as Photoshop does in its Indexed Color and Bitmap
/// documents (#12041).
///
/// Both halves of the answer come from the issue:
/// - the modes: Indexed Color and Bitmap are the two documents that keep no type layer;
/// - the text: only the horizontal point text the measurement describes - the tool "still lets you
/// click and type" and the commit leaves "a selection in the shape of the typed glyphs". Paragraph
/// (box) text and vertical type are on its *Not measured* list, whose rule is that an unmeasured
/// case keeps today's behaviour - and today's behaviour is the outcome that makes sense here
/// anyway: a coverage mask cannot give back a box that reflows or a column of stacked lines, so
/// the selection would end the editability the layer exists for. The Type Mask tools keep turning
/// both into the selection, as they do today: there the user asked for one.
///
/// The check belongs to the Type tool's commit (the Type Mask tools' `type.createSelection` with
/// `removeLayer`, which it already runs for `ed.mask`) and *not* to the `type.create` command, even
/// though a colour-mode check there is what looks simplest:
/// - `type.create` is the primitive the tools build the layer they edit and show on canvas with
/// (`pointer_up` in `ui-egui`), and Preferences > Type > "Fill new type layers with placeholder
/// text" (on by default) already gives that first call non-empty text. Branching there would make
/// the click produce a selection and no layer, so there would be nothing to type into - while the
/// reference application still lets you click and type in these modes and shows the text while
/// editing. Only its commit differs.
/// - `type.create` is also what automation, actions and a script's new text layer go through, and
/// the measured difference is the tool's.
pub fn commits_as_selection(mode: ColorMode, t: &TextLayer) -> bool {
let measured = matches!(t.shape, TextShape::Point) && t.orientation == Orientation::Horizontal;
measured && matches!(mode, ColorMode::Indexed | ColorMode::Bitmap)
}
/// Name the step the Type tool's commit made in such a document (#12041). The commit runs the Type
/// Mask tools' `type.createSelection` with `removeLayer` - the same conversion, coalesced into the
/// one step of the typing session - and that command names the step "Type Mask", while Photoshop's
/// history state here is the type layer's own name.
///
/// An edit that does not carry the session's `coalesce` key (the Alt+arrow kerning step, which is
/// deliberately one state per press) ends the session's step, exactly as it does for the Type Mask
/// tools and for the plain type layer's rename on commit; the conversion is then a state of its own
/// and takes this name too. Photoshop repeats a state name whenever the same thing happens again,
/// so the two states read as the two type-layer steps they are.
pub fn name_selection_commit(s: &mut Session) {
if let Some(st) = s.active_mut() {
st.history.set_current_label(NEW_TYPE_LAYER_LABEL);
}
}
const CHAR_PARAMS: &str = r##""font":str,"fontStyle":str,"weight":100..900,"italic":bool,"size":0.1..=1296 pt,"color":"#rrggbb"|[r,g,b,a],"tracking":-1000..=10000 (1/1000 em),"leading":pt|"auto","baselineShift":pt,"horizontalScale":%,"verticalScale":%,"underline":bool,"strikethrough":bool,"fauxBold":bool,"fauxItalic":bool,"kerning":1/1000em (manual, after each character)|"metrics"|"optical"|"off","caps":"normal|small|all","baseline":"normal|superscript|subscript","ligatures":bool,"discretionaryLigatures":bool,"features":{"ss01":1},"variations":{"wght":650},"language":str"##;
pub fn specs() -> Vec<CommandSpec> {
@@ -953,7 +1003,7 @@ pub fn specs() -> Vec<CommandSpec> {
let mut t = new_text_layer(s, p, "type.create")?;
let given = p.get("name").and_then(Value::as_str).map(str::to_string);
let name = given.clone().unwrap_or_else(|| layer_name(&t.text));
let id = s.edit("New Type Layer", |doc, active| {
let id = s.edit(NEW_TYPE_LAYER_LABEL, |doc, active| {
refresh(doc, &mut t);
let id = crate::layer_place::insert_new(doc, *active, Layer::new(name, LayerContent::Text(t)), crate::layer_place::Place::AutoEditable);
*active = Some(id);
@@ -0,0 +1,287 @@
//! #12041: committing Type-tool text in an Indexed Color or a Bitmap document.
//!
//! The reference application still lets you click and type there and shows the text while editing;
//! the commit leaves **no type layer** and a selection in the shape of the glyphs, as one history
//! state named "New Type Layer", and paints nothing. [`super::type_cmds::commits_as_selection`] is
//! that mode check and [`super::type_cmds::name_selection_commit`] the step's name; the conversion
//! is the Type Mask tools' `type.createSelection` with `removeLayer`, coalesced into the typing
//! session, which is what [`commit`] below runs and what `ui-egui`'s `commit_here` now does for the
//! Type tool in these modes.
//!
//! `type.create` itself stays mode-agnostic on purpose, and
//! [`the_type_layer_command_keeps_making_the_tools_working_layer`] pins that: the tools make the
//! layer they edit and show on canvas with that command, on the first click already with text in it
//! when Preferences > Type > "Fill new type layers with placeholder text" is on (the default), so a
//! mode branch there would take away the layer the session types into.
//!
//! The issue measures the horizontal point text you click and type, and lists paragraph text and
//! vertical type under *Not measured*, where its rule is that today's behaviour stays:
//! [`only_the_measured_horizontal_point_text_converts_in_these_modes`] pins that half of the check,
//! and [`an_uncoalesced_edit_between_typing_and_the_commit_splits_the_states`] what happens to the
//! states when an edit outside the session's coalesce group comes between the typing and the commit.
use super::type_cmds::{commits_as_selection, name_selection_commit, new_text_layer};
use super::*;
use photocraft_doc::text::{Orientation, TextShape};
/// The typing session's coalesce key, as `ui-egui`'s `session_key` gives one.
const SESSION: &str = "type-session-12041";
/// The text the tool commits, at a baseline inside every document used here. `coalesce` for the
/// tool's own calls (one step for the session), without it for a script's or the pin's.
fn typed(coalesce: bool) -> Value {
let mut p = json!({ "text": "Hi", "x": 20, "y": 80, "size": 48 });
if coalesce {
p["coalesce"] = json!(SESSION);
}
p
}
/// A blank RGB document, to be converted to the mode under test.
fn blank() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 240, "height": 120, "background": "transparent"})).unwrap();
s
}
fn indexed() -> Session {
let mut s = blank();
s.execute("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap();
assert_eq!(mode(&s), ColorMode::Indexed, "the setup made an Indexed Color document");
s
}
fn bitmap() -> Session {
let mut s = blank();
s.execute("image.mode.grayscale", json!({})).unwrap();
s.execute("image.mode.bitmap", json!({"method": "threshold", "frequency": 12, "shape": "diamond"})).unwrap();
assert_eq!(mode(&s), ColorMode::Bitmap, "the setup made a Bitmap document");
s
}
fn mode(s: &Session) -> ColorMode {
s.active().unwrap().doc.mode
}
/// The Type tool's commit of the session's working layer in a document [`commits_as_selection`]
/// names: the Type Mask tools' conversion, in the session's one step, which keeps the name the step
/// was opened with.
fn commit(s: &mut Session, layer: u64) {
s.execute("type.createSelection", json!({"layer": layer, "removeLayer": true, "operation": "new", "coalesce": SESSION})).unwrap();
name_selection_commit(s);
}
fn text_layers(s: &Session) -> usize {
s.active().unwrap().doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).count()
}
fn layers(s: &Session) -> usize {
s.active().unwrap().doc.walk().len()
}
/// The selection's coverage over the whole canvas, in document pixels.
fn coverage(s: &Session) -> Vec<f32> {
let d = s.active().unwrap().doc.clone();
let b = d.bounds();
let mut out = Vec::new();
for y in b.y0..b.y1 {
for x in b.x0..b.x1 {
out.push(d.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)));
}
}
out
}
/// The selection's bounds, as its corners.
fn selection_corners(s: &Session) -> Option<[i32; 4]> {
s.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds()).map(|r| [r.x0, r.y0, r.x1, r.y1])
}
/// Every layer's pixels, quantised: what the commit must leave exactly as it was.
fn pixels(s: &Session) -> Vec<u8> {
let d = s.active().unwrap().doc.clone();
let b = d.bounds();
let mut out = Vec::new();
for (_, _, l) in d.walk() {
let Some(surface) = l.surface() else { continue };
for y in b.y0..b.y1 {
for x in b.x0..b.x1 {
out.extend(surface.rgba(x, y).map(|v| (v * 255.0).round() as u8));
}
}
}
out
}
fn history(s: &Session) -> Vec<String> {
s.active().unwrap().history.entries()
}
#[test]
fn committing_in_indexed_color_or_bitmap_leaves_the_glyphs_selected_and_no_layer() {
for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] {
let mut s = make();
let (steps, layers_before, pixels_before) = (history(&s).len(), layers(&s), pixels(&s));
// The tool's session: a type layer to edit and show while typing, as measured.
let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap();
assert_eq!(text_layers(&s), 1, "{name}: typing happens on a layer the tool can show");
commit(&mut s, layer);
assert_eq!(text_layers(&s), 0, "{name}: committing leaves no type layer");
assert_eq!(layers(&s), layers_before, "{name}: the working layer went with it");
assert!(s.active().unwrap().doc.selection.is_some(), "{name}: the glyphs are selected");
let selected = s.active().unwrap().doc.selection.as_ref().unwrap();
assert!(!selected.content_bounds().is_empty(), "{name}: the selection has a shape");
assert!(coverage(&s).iter().any(|v| *v > 0.0), "{name}: the selected pixels are the glyphs'");
assert_eq!(pixels(&s), pixels_before, "{name}: the commit paints nothing");
// One step for the whole session, named as Photoshop names it.
let h = history(&s);
assert_eq!(h.len(), steps + 1, "{name}: the session is one history state: {h:?}");
assert_eq!(h.last().map(String::as_str), Some("New Type Layer"), "{name}: its name");
// And undoing that one state gives the document back as it was.
s.execute("edit.undo", json!({})).unwrap();
assert!(s.active().unwrap().doc.selection.is_none(), "{name}: undo takes the selection");
assert_eq!(layers(&s), layers_before, "{name}: undo takes the whole session");
assert_eq!(pixels(&s), pixels_before, "{name}: nothing else was changed");
}
}
#[test]
fn the_selection_is_the_glyph_shape_the_type_mask_of_the_same_text_makes() {
for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] {
let mut s = make();
let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap();
commit(&mut s, layer);
let (got, got_bounds) = (coverage(&s), selection_corners(&s));
// The pin: the same text straight through the Type Mask command.
let mut pin = make();
pin.execute("type.createSelection", typed(false)).unwrap();
assert_eq!(got_bounds, selection_corners(&pin), "{name}: same selection bounds");
assert_eq!(got, coverage(&pin), "{name}: same selection coverage");
}
}
#[test]
fn rgb_grayscale_cmyk_and_lab_keep_making_type_layers_at_every_depth() {
for (id, want) in [("rgb", ColorMode::Rgb), ("gray", ColorMode::Grayscale), ("cmyk", ColorMode::Cmyk), ("lab", ColorMode::Lab)] {
for depth in [8, 16, 32] {
let mut s = Session::new();
s.execute("file.new", json!({"width": 240, "height": 120, "mode": id, "depth": depth, "background": "transparent"})).unwrap();
assert_eq!(mode(&s), want, "{id} at {depth} bit: the document really is that mode");
let point = new_text_layer(&s, &typed(false), "type.create").unwrap();
assert!(!commits_as_selection(want, &point), "{id} keeps type layers");
let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap();
// Today's commit: rename the session's layer in the same step, select nothing.
let name = super::type_cmds::layer_name("Hi");
s.execute("type.edit", json!({"layer": layer, "name": name, "coalesce": SESSION})).unwrap();
assert_eq!(text_layers(&s), 1, "{id} at {depth} bit keeps its type layer");
assert!(s.active().unwrap().doc.selection.is_none(), "{id} at {depth} bit selects nothing");
let h = history(&s);
assert_eq!(h.len(), 2, "{id} at {depth} bit: open plus one step for the session: {h:?}");
assert_eq!(h.last().map(String::as_str), Some("New Type Layer"), "{id} at {depth} bit keeps the step's name");
}
}
}
#[test]
fn the_type_layer_command_keeps_making_the_tools_working_layer_in_these_modes() {
// `type.create` is the primitive the Type tools create the layer they edit with (and scripts and
// actions their text layers with), so the colour-mode branch is the commit's, not its own.
for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] {
let mut s = make();
let id = s.execute("type.create", typed(false)).unwrap()["layer"].as_u64().unwrap();
assert!(matches!(s.active().unwrap().doc.layer(LayerId(id)).unwrap().content, LayerContent::Text(_)), "{name}: the command still makes the layer");
assert!(s.active().unwrap().doc.selection.is_none(), "{name}: and selects nothing itself");
assert_eq!(history(&s).last().map(String::as_str), Some("New Type Layer"), "{name}: its own step name");
}
}
#[test]
fn a_refused_conversion_leaves_the_typed_text_and_the_document_alone() {
// The commit's fallback in `ui-egui` keeps today's type layer when the conversion is refused,
// so the typed text is not lost with a selection that was never made. Here the document would
// have to keep no layer at all, which is what `type.createSelection` with `removeLayer` refuses.
for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] {
let mut s = make();
let only = s.active().unwrap().doc.layers[0].id.0;
let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap();
s.execute("layer.delete", json!({"layer": only})).unwrap();
let (pixels_before, steps, label) = (pixels(&s), history(&s).len(), history(&s).last().cloned());
assert!(
s.execute("type.createSelection", json!({"layer": layer, "removeLayer": true, "operation": "new", "coalesce": SESSION})).is_err(),
"{name}: the conversion is refused"
);
// `commit_here` stops there and keeps the layer, so the step is never renamed either.
assert_eq!(text_layers(&s), 1, "{name}: the typed text stays as a type layer");
assert!(s.active().unwrap().doc.selection.is_none(), "{name}: nothing was selected");
assert_eq!(pixels(&s), pixels_before, "{name}: the refused step painted nothing");
assert_eq!(history(&s).len(), steps, "{name}: the refused step is no new state");
assert_eq!(history(&s).last().cloned(), label, "{name}: the refused conversion renames nothing");
}
}
/// The measurement covers horizontal point text. Paragraph (box) text and vertical type are on the
/// issue's *Not measured* list, where its rule is that today's behaviour stays - and a coverage mask
/// could not give a reflowing box or a stacked column back anyway, so their editable layer stays.
#[test]
fn only_the_measured_horizontal_point_text_converts_in_these_modes() {
let s = indexed();
let point = new_text_layer(&s, &typed(false), "type.create").unwrap();
assert!(matches!(point.shape, TextShape::Point) && point.orientation == Orientation::Horizontal, "the fixture is horizontal point text");
let mut box_params = typed(false);
box_params["box"] = json!([20.0, 20.0, 180.0, 80.0]);
let paragraph = new_text_layer(&s, &box_params, "type.create").unwrap();
assert!(matches!(paragraph.shape, TextShape::Box { .. }), "the fixture is paragraph text");
let mut vertical_params = typed(false);
vertical_params["orientation"] = json!("vertical");
let vertical = new_text_layer(&s, &vertical_params, "type.create").unwrap();
assert_eq!(vertical.orientation, Orientation::Vertical, "the fixture is vertical text");
for mode in [ColorMode::Indexed, ColorMode::Bitmap] {
assert!(commits_as_selection(mode, &point), "{mode:?}: the measured text becomes the selection");
assert!(!commits_as_selection(mode, &paragraph), "{mode:?}: paragraph text keeps its type layer");
assert!(!commits_as_selection(mode, &vertical), "{mode:?}: vertical text keeps its type layer");
}
}
/// An edit that does not carry the session's `coalesce` key ends its coalesce group - in the tool
/// that is the deliberately per-press Alt+arrow kerning step. The commit then makes a state of its
/// own, which is what the Type Mask tools' commit and the plain layer's rename do in the same
/// situation today; nothing is mis-named and nothing else moves.
#[test]
fn an_uncoalesced_edit_between_typing_and_the_commit_splits_the_states() {
for (name, make) in [("Indexed Color", indexed as fn() -> Session), ("Bitmap", bitmap as fn() -> Session)] {
let mut s = make();
let layer = s.execute("type.create", typed(true)).unwrap()["layer"].as_u64().unwrap();
// The stand-in for that kerning press: a real edit under no coalesce key.
s.execute("type.edit", json!({"layer": layer, "antialias": "sharp"})).unwrap();
let before = history(&s);
assert_eq!(before.last().map(String::as_str), Some("Edit Type"), "{name}: the unkeyed edit is a state of its own");
commit(&mut s, layer);
let h = history(&s);
assert_eq!(h.len(), before.len() + 1, "{name}: the commit is a further state once the group ended: {h:?}");
assert_eq!(h.last().map(String::as_str), Some("New Type Layer"), "{name}: named for the type layer either way");
assert_eq!(h[h.len() - 2].as_str(), "Edit Type", "{name}: the edit between them keeps its own name");
assert_eq!(text_layers(&s), 0, "{name}: still no type layer is left");
assert!(s.active().unwrap().doc.selection.is_some(), "{name}: still the glyphs are selected");
s.execute("edit.undo", json!({})).unwrap();
assert!(s.active().unwrap().doc.selection.is_none(), "{name}: one undo takes the conversion");
assert_eq!(text_layers(&s), 1, "{name}: which brings the working layer back, as the mask tools' undo does");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(text_layers(&s), 1, "{name}: the next undo takes the unkeyed edit, not the session");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(text_layers(&s), 0, "{name}: and the third one takes the typing session");
}
}
+6 -18
View File
@@ -533,9 +533,8 @@ fn stroke_with_command(s: &mut Session, p: &Value, cmd: &str, lines: &[vector::P
params.remove(k);
}
let journal = s.journal.len();
let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
let r = crate::analysis_cmds::compound(s, "Stroke Path", |s| {
// The union of what each subpath's command changed; None when one of them didn't say.
let mut dmg = Some(Rect::EMPTY);
for pl in lines {
let pts = stroke_points(&pl.pts, pl.closed, simulate);
if pts.is_empty() {
@@ -544,25 +543,14 @@ fn stroke_with_command(s: &mut Session, p: &Value, cmd: &str, lines: &[vector::P
let mut call = params.clone();
call.insert("points".into(), Value::Array(pts.iter().map(|q| json!([q.x, q.y, q.pressure])).collect()));
s.execute(cmd, Value::Object(call))?;
let r = s.active().and_then(|d| d.last_damage);
dmg = dmg.zip(r).map(|(a, b)| {
if a.is_empty() {
b
} else if b.is_empty() {
a
} else {
a.union(&b)
}
});
}
Ok(dmg)
Ok(())
});
s.journal.truncate(journal);
let dmg = r?;
if let Some(st) = s.active_mut() {
st.last_damage = dmg;
}
let dmg = dmg.unwrap_or_else(|| s.active().map_or(Rect::EMPTY, |d| d.doc.bounds()));
r?;
// One subpath keeps its command's damage; several are one span, which `Session::dispatch`
// reports. The result says what changed either way.
let dmg = s.active().and_then(|st| crate::layer_multi_cmds::step_damage(&before, &st.doc).or(Some(st.doc.bounds()))).unwrap_or(Rect::EMPTY);
Ok(json!({ "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] }))
}
+48 -23
View File
@@ -59,14 +59,20 @@ pub fn warp_bounds(doc: &Document, layer: &Layer) -> Rect {
crate::transform_cmds::transform_bounds(doc, layer)
}
/// A smart object's stored warp expressed in document space (for editing), if it has one.
/// A smart object's stored warp expressed in document space (for editing), if it has one. A
/// cylinder under a placement that only scales and moves stays a cylinder, with its seven values
/// in document space, so Warp mode shows its own handles; under any other placement it is its
/// mesh, a custom warp, like every other stored warp.
pub fn smart_warp_doc_space(layer: &Layer) -> Option<Warp> {
let LayerContent::Smart(sm) = &layer.content else { return None };
let w = sm.warp.as_ref()?;
let t = crate::smart_cmds::placement(sm);
let mesh = w.to_mesh(1, 1).map_points(|p| hom_apply(&t, p));
let corners = [[w.bounds[0], w.bounds[1]], [w.bounds[2], w.bounds[1]], [w.bounds[2], w.bounds[3]], [w.bounds[0], w.bounds[3]]].map(|p| hom_apply(&t, p));
let b = corners.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);
if let Some(c) = cylinder_through(w, &t, b) {
return Some(c);
}
let mesh = w.to_mesh(1, 1).map_points(|p| hom_apply(&t, p));
Some(Warp::custom(mesh, b))
}
@@ -128,41 +134,60 @@ const CYLINDER_VALUES: &str =
"a cylinder needs `values`: seven numbers [left, bottom, right, top, top depth, bottom depth, wrap 0..1], the right silhouette right of the left one";
const CYLINDER_SHAPE: &str = "a cylinder is horizontal, with no hDistort or vDistort";
/// A document-space cylinder `w` stored on a smart object, whose placement's inverse is `inv` and
/// whose warp box `w.bounds` lands on `sb` in source space. A placement that only scales and
/// moves keeps it a cylinder (written to PSD as one): the silhouettes and edges map, and the
/// ellipses' depth, in units of the half axis, follows the change of aspect. Otherwise (rotated,
/// skewed, flipped, in perspective) it becomes its mesh, a custom warp.
fn cylinder_in_source(w: &Warp, inv: &Homography, sb: [f64; 4]) -> Option<Warp> {
let m = inv.0;
/// The cylinder `w` carried through `h` over the box `b` (its warp box's image), when `h` only
/// scales and moves: the silhouettes and edges map, and the ellipses' depth, in units of the half
/// axis, follows the change of aspect. `None` for any other map (rotated, skewed, flipped, in
/// perspective), or when `w` is not a cylinder: the mesh is the only way to carry it then.
fn cylinder_through(w: &Warp, h: &Homography, b: [f64; 4]) -> Option<Warp> {
let m = h.0;
let axis_aligned = m[8] != 0.0 && m[1] == 0.0 && m[3] == 0.0 && m[6] == 0.0 && m[7] == 0.0;
let (sx, sy) = (m[0] / m[8], m[4] / m[8]);
if axis_aligned && sx > 0.0 && sy > 0.0 && w.values.len() == 7 {
let v = &w.values;
let (x, y) = (|v: f64| sx * v + m[2] / m[8], |v: f64| sy * v + m[5] / m[8]);
let k = sy / sx;
if let Some(c) = Warp::cylinder(&[x(v[0]), y(v[1]), x(v[2]), y(v[3]), v[4] * k, v[5] * k, v[6]], sb) {
return Some(c);
}
if w.style != WarpStyle::Cylinder || !axis_aligned || !(sx > 0.0 && sy > 0.0) {
return None;
}
let v: [f64; 7] = w.values.as_slice().try_into().ok()?;
let (x, y) = (|v: f64| sx * v + m[2] / m[8], |v: f64| sy * v + m[5] / m[8]);
let k = sy / sx;
Warp::cylinder(&[x(v[0]), y(v[1]), x(v[2]), y(v[3]), v[4] * k, v[5] * k, v[6]], b)
}
/// A document-space cylinder `w` stored on a smart object, whose placement's inverse is `inv` and
/// whose warp box `w.bounds` lands on `sb` in source space. A placement that only scales and
/// moves keeps it a cylinder (written to PSD as one, [`cylinder_through`]). Otherwise (rotated,
/// skewed, flipped, in perspective) it becomes its mesh, a custom warp.
fn cylinder_in_source(w: &Warp, inv: &Homography, sb: [f64; 4]) -> Option<Warp> {
if let Some(c) = cylinder_through(w, inv, sb) {
return Some(c);
}
let mesh = w.to_mesh(1, 1).map_points(|p| hom_apply(inv, p));
Some(Warp::custom(mesh, sb))
}
/// Whether the custom warp `w` is exactly what Warp mode shows for `layer`'s stored cylinder
/// ([`smart_warp_doc_space`]: its mesh over the same box), so committing it untouched changes
/// nothing. Stored as a custom warp instead, the cylinder would be lost, as a PSD keeps it only
/// as `warpCylinder` (#4112).
/// Whether `w` is exactly what Warp mode shows for `layer`'s stored cylinder
/// ([`smart_warp_doc_space`]): the same cylinder over the same box, or its mesh (what a rotated
/// placement shows, and what Warp mode showed before it had a cylinder editor), so committing it
/// untouched changes nothing. Stored as a custom warp instead, the cylinder would be lost, as a
/// PSD keeps it only as `warpCylinder` (#4112).
fn is_stored_cylinder(layer: &Layer, w: &Warp) -> bool {
let LayerContent::Smart(sm) = &layer.content else { return false };
if w.style != WarpStyle::Custom || sm.warp.as_ref().is_none_or(|s| s.style != WarpStyle::Cylinder) {
if sm.warp.as_ref().is_none_or(|s| s.style != WarpStyle::Cylinder) {
return false;
}
let (Some(shown), Some(m)) = (smart_warp_doc_space(layer), w.mesh.as_ref()) else { return false };
let Some(shown) = smart_warp_doc_space(layer) else { return false };
let Some(o) = shown.mesh.as_ref() else { return false };
let tol = 1e-6 * (1.0 + o.points.iter().flatten().chain(&shown.bounds).fold(0.0f64, |a, v| a.max(v.abs())));
let near = |a: &[f64], b: &[f64]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol);
o.us == m.us && o.vs == m.vs && near(&shown.bounds, &w.bounds) && near(o.points.as_flattened(), m.points.as_flattened())
// A cylinder's depths and wrap are dimensionless: at a large document offset the coordinate
// tolerance would pass off a change of wrap as none.
let near_values =
|a: &[f64], b: &[f64]| a.len() == b.len() && a.iter().zip(b).enumerate().all(|(i, (x, y))| (x - y).abs() <= if i < 4 { tol } else { 1e-9 });
match (w.style, w.mesh.as_ref()) {
(WarpStyle::Cylinder, _) => shown.style == WarpStyle::Cylinder && near(&shown.bounds, &w.bounds) && near_values(&shown.values, &w.values),
(WarpStyle::Custom, Some(m)) => {
o.us == m.us && o.vs == m.vs && near(&shown.bounds, &w.bounds) && near(o.points.as_flattened(), m.points.as_flattened())
}
_ => false,
}
}
/// A Background is turned into a normal layer by the caller first
+57 -14
View File
@@ -166,9 +166,11 @@ fn smart_object_cylinder_is_stored_in_source_space() {
assert_eq!(w.mesh.as_ref().map(|m| (m.nx(), m.ny())), Some((13, 4)));
}
/// Warp mode shows a stored cylinder as its mesh, and Enter commits that mesh untouched: the
/// smart object keeps its cylinder (else the next PSD save writes no warp), while a moved
/// point still makes it a custom warp.
/// Warp mode shows a stored cylinder as a cylinder in document space (its handles edit the
/// seven values), and Enter commits it untouched: the smart object keeps its cylinder (else the
/// next PSD save writes no warp). The same holds for its mesh, which is what a rotated placement
/// shows and what Warp mode showed before it had a cylinder editor. A changed value stays a
/// cylinder; a moved mesh point makes it a custom warp.
#[test]
fn untouched_cylinder_committed_from_warp_mode_stays_a_cylinder() {
for scale in [100, 150] {
@@ -188,30 +190,71 @@ fn untouched_cylinder_committed_from_warp_mode_stays_a_cylinder() {
let cylinder = stored(&s);
assert_eq!(cylinder.style, WarpStyle::Cylinder, "{scale}");
let shown = smart_warp_doc_space(s.active().unwrap().doc.layer(id).unwrap()).unwrap();
assert_eq!(shown.style, WarpStyle::Custom);
s.execute("select.all", json!({})).unwrap();
let (sel, steps) = (s.active().unwrap().doc.selection.clone(), s.active().unwrap().history.past_len());
let r = s.execute("edit.transform.warp", json!({"layer": id.0, "rect": shown.bounds, "warp": shown, "interpolation": "bicubic"})).unwrap();
assert_eq!(r["changed"], false, "{scale}");
assert_eq!(stored(&s), cylinder, "{scale}: untouched");
let st = s.active().unwrap();
assert!(st.doc.selection == sel && st.history.past_len() == steps, "{scale}: no step, the selection stays");
assert_eq!(shown.style, WarpStyle::Cylinder, "{scale}: shown as a cylinder");
for (v, sv) in values.iter().zip(&shown.values) {
assert!((v - sv).abs() < 1e-6, "{scale}: the values come back in document space: {values:?} vs {:?}", shown.values);
}
let as_mesh = Warp::custom(shown.to_mesh(1, 1), shown.bounds);
for (what, untouched) in [("cylinder", shown.clone()), ("mesh", as_mesh.clone())] {
s.execute("select.all", json!({})).unwrap();
let (sel, steps) = (s.active().unwrap().doc.selection.clone(), s.active().unwrap().history.past_len());
let r = s.execute("edit.transform.warp", json!({"layer": id.0, "rect": untouched.bounds, "warp": untouched, "interpolation": "bicubic"})).unwrap();
assert_eq!(r["changed"], false, "{scale} {what}");
assert_eq!(stored(&s), cylinder, "{scale} {what}: untouched");
let st = s.active().unwrap();
assert!(st.doc.selection == sel && st.history.past_len() == steps, "{scale} {what}: no step, the selection stays");
}
// The same mesh over another box is another warp.
let mut wider = shown.clone();
let mut wider = as_mesh.clone();
wider.bounds[2] += 10.0;
s.execute("edit.transform.warp", json!({"layer": id.0, "rect": wider.bounds, "warp": wider})).unwrap();
assert_eq!(stored(&s).style, WarpStyle::Custom, "{scale}: other box");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(stored(&s), cylinder);
let mut moved = shown.clone();
let mut moved = as_mesh.clone();
if let Some(m) = moved.mesh.as_mut() {
m.points[20][1] += 5.0;
}
s.execute("edit.transform.warp", json!({"layer": id.0, "rect": moved.bounds, "warp": moved})).unwrap();
assert_eq!(stored(&s).style, WarpStyle::Custom, "{scale}: edited");
assert_eq!(stored(&s).style, WarpStyle::Custom, "{scale}: edited mesh");
s.execute("edit.undo", json!({})).unwrap();
// A value changed by a handle commits as a cylinder with that value, one step.
let steps = s.active().unwrap().history.past_len();
let mut deeper = shown.values.clone();
deeper[4] = 0.45;
let r = s.execute("edit.transform.warp", json!({"layer": id.0, "rect": shown.bounds, "warp": Warp::cylinder(&deeper, shown.bounds).unwrap()})).unwrap();
assert_eq!(r["changed"], true, "{scale}: edited cylinder");
let after = stored(&s);
assert_eq!(after.style, WarpStyle::Cylinder, "{scale}: still a cylinder");
assert!((after.values[4] - 0.45 * cylinder.values[4] / 0.3).abs() < 1e-9, "{scale}: the depth follows, in source units: {:?}", after.values);
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{scale}: one step");
}
}
/// Under a rotated placement a stored cylinder has no document-space values: Warp mode shows its
/// mesh, and committing that mesh untouched still changes nothing.
#[test]
fn a_rotated_cylinder_is_shown_as_its_mesh() {
let mut s = session(8);
s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
let id = s.active().unwrap().active_layer.unwrap();
s.execute("layer.smartObjects.warp", json!({"style": "cylinder", "values": CYL, "rect": [10, 10, 60, 40]})).unwrap();
s.execute("edit.transform", json!({"rotate": 30})).unwrap();
let stored = |s: &Session| {
let st = s.active().unwrap();
let LayerContent::Smart(sm) = &st.doc.layer(id).unwrap().content else { panic!("smart") };
sm.warp.clone().unwrap()
};
assert_eq!(stored(&s).style, WarpStyle::Cylinder, "the placement turned, the source warp stays");
let shown = smart_warp_doc_space(s.active().unwrap().doc.layer(id).unwrap()).unwrap();
assert_eq!(shown.style, WarpStyle::Custom);
assert!(shown.values.is_empty());
let steps = s.active().unwrap().history.past_len();
let r = s.execute("edit.transform.warp", json!({"layer": id.0, "rect": shown.bounds, "warp": shown})).unwrap();
assert_eq!(r["changed"], false);
assert_eq!(s.active().unwrap().history.past_len(), steps);
}
#[test]
fn identity_and_bend_zero_are_no_ops_at_every_depth() {
for depth in [8u64, 16, 32] {
+1 -1
View File
@@ -123,7 +123,7 @@ pub(crate) fn refusal(s: &Session, id: &str, p: &Value) -> Option<String> {
return Some("Move and transforms on several colour channels are not implemented yet".into());
}
if id == "filter.cameraRaw" {
return Some("Camera Raw requires the composite or one colour channel".into());
return Some("RAW Develop requires the composite or one colour channel".into());
}
None
}
+16 -1
View File
@@ -24,8 +24,13 @@ pub struct DocState {
pub pcraft_cache: photocraft_io::PcraftExportCache,
/// How much of `revision` came from view-only changes (channel eyes, targeting): pixel caches can ignore those.
pub view_revision: u64,
/// Area changed by the latest revision (None = assume everything changed).
/// Area changed since revision [`DocState::damage_from`] (None = assume everything changed):
/// the latest revision's, or a whole command's when it made several.
pub last_damage: Option<photocraft_geom::Rect>,
/// `(from, to)`: the command that moved `revision` from `from` to `to` in more than one step,
/// whose whole span `last_damage` covers. Written only by `Session::dispatch`; any later
/// revision makes it stale, so [`DocState::damage_from`] falls back to one revision.
pub(crate) damage_span: Option<(u64, u64)>,
/// Coalescing key of the latest history step (see [`Session::execute`]'s `coalesce` param).
pub coalesce: Option<String>,
/// Channels panel: targeted channel and eye toggles (view state, not history).
@@ -108,6 +113,7 @@ impl DocState {
pcraft_cache: Default::default(),
view_revision: 0,
last_damage: None,
damage_span: None,
coalesce: None,
channel_view,
isolated_layers: Vec::new(),
@@ -144,6 +150,15 @@ impl DocState {
pub(crate) fn keeps_clean(&self, before: &Document) -> bool {
self.saved_revision == self.revision && layer_multi_cmds::selection_only_change(before, &self.doc)
}
/// The revision [`DocState::last_damage`] is measured from: the revision before the command
/// that made it, or the previous revision. A canvas that showed any revision from this one
/// up to (not including) `revision` needs only `last_damage` redrawn.
pub fn damage_from(&self) -> u64 {
match self.damage_span {
Some((from, to)) if to == self.revision => from,
_ => self.revision.saturating_sub(1),
}
}
/// Move to the next revision; `keep_clean` (from [`Self::keeps_clean`]) moves the saved
/// revision with it.
pub(crate) fn bump_revision(&mut self, keep_clean: bool) {
+2
View File
@@ -84,6 +84,7 @@ pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {
return Some(fp);
}
Some(match id {
"filter.blur.average" => FilterParams::Average,
"filter.blur.gaussianBlur" => FilterParams::GaussianBlur { radius: f(p, "radius", 1.0).clamp(0.1, 1000.0) },
"filter.blur.boxBlur" => FilterParams::BoxBlur { radius: f(p, "radius", 1.0).clamp(1.0, 2000.0) },
"filter.blur.motionBlur" => FilterParams::MotionBlur { angle: f(p, "angle", 0.0), distance: f(p, "distance", 10.0).clamp(1.0, 2000.0) },
@@ -471,6 +472,7 @@ macro_rules! filter_cmd {
pub fn specs() -> Vec<CommandSpec> {
vec![
filter_cmd!("filter.blur.gaussianBlur", "Gaussian Blur…", ["Filter", "Blur"], r##"{"radius":0.1..1000=1}"##),
filter_cmd!("filter.blur.average", "Average", ["Filter", "Blur"], "{}"),
filter_cmd!("filter.blur.blur", "Blur", ["Filter", "Blur"], "{}"),
filter_cmd!("filter.blur.blurMore", "Blur More", ["Filter", "Blur"], "{}"),
filter_cmd!("filter.sharpen.sharpen", "Sharpen", ["Filter", "Sharpen"], "{}"),
Loaded 100 of 401 files, more files were not shown because too many files have changed in this diff. Show more