diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index bac9633320..df4e9a2905 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -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) | | 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 | | 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 | (`icons/.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 | (`icons/.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 | 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 | diff --git a/Cargo.lock b/Cargo.lock index 434e4b6aa8..f650cccdda 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index f5fafa868d..cd2f69a665 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/apps/photocraft-cli/Cargo.toml b/apps/photocraft-cli/Cargo.toml index 4ddde07142..7640483f44 100644 --- a/apps/photocraft-cli/Cargo.toml +++ b/apps/photocraft-cli/Cargo.toml @@ -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 } diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index a5acb4557b..2baf000039 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -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, + /// 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)] diff --git a/apps/photocraft-cli/src/document.rs b/apps/photocraft-cli/src/document.rs index ab9e3cfd35..5541da11a6 100644 --- a/apps/photocraft-cli/src/document.rs +++ b/apps/photocraft-cli/src/document.rs @@ -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)?; diff --git a/apps/photocraft/src/mac_menu.rs b/apps/photocraft/src/mac_menu.rs index f8a7c8c689..aea005753e 100644 --- a/apps/photocraft/src/mac_menu.rs +++ b/apps/photocraft/src/mac_menu.rs @@ -254,7 +254,7 @@ impl Backend for MacMenu { pub fn install(ctx: &egui::Context, app: &photocraft_ui_egui::PhotocraftApp) -> Option { 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); diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 545fc86eec..7c0fbf763e 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -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) -> 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]| { diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index fb2188cdab..a89a1a327e 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -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] diff --git a/apps/photocraft/src/updates.rs b/apps/photocraft/src/updates.rs index a11a7b63c9..50bba88de1 100644 --- a/apps/photocraft/src/updates.rs +++ b/apps/photocraft/src/updates.rs @@ -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> { + 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)?; diff --git a/assets/icons/panel-left.svg b/assets/icons/panel-left.svg new file mode 100644 index 0000000000..60642c396f --- /dev/null +++ b/assets/icons/panel-left.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/vertical-align-bottom.svg b/assets/icons/vertical-align-bottom.svg new file mode 100644 index 0000000000..09931ffd77 --- /dev/null +++ b/assets/icons/vertical-align-bottom.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/assets/icons/vertical-align-middle.svg b/assets/icons/vertical-align-middle.svg new file mode 100644 index 0000000000..019f70872d --- /dev/null +++ b/assets/icons/vertical-align-middle.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/assets/icons/vertical-align-top.svg b/assets/icons/vertical-align-top.svg new file mode 100644 index 0000000000..c5269fe99a --- /dev/null +++ b/assets/icons/vertical-align-top.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/contributors/people.toml b/contributors/people.toml index a2ead57598..81f432e436 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -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 diff --git a/crates/algo/src/average.rs b/crates/algo/src/average.rs new file mode 100644 index 0000000000..982ec7cb6f --- /dev/null +++ b/crates/algo/src/average.rs @@ -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 { + 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 { + 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; diff --git a/crates/algo/src/average/tests.rs b/crates/algo/src/average/tests.rs new file mode 100644 index 0000000000..c7158bd743 --- /dev/null +++ b/crates/algo/src/average/tests.rs @@ -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]); + } + } +} diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index ad72954a22..d1c797b228 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -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 { 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; diff --git a/crates/algo/src/liquify.rs b/crates/algo/src/liquify.rs index 40865c09b2..1788873ccd 100644 --- a/crates/algo/src/liquify.rs +++ b/crates/algo/src/liquify.rs @@ -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, /// Where the brush stroke in progress stands, so dab spacing runs on across its segments. cursor: Option, + /// 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, +} + +/// 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)> = + 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)); diff --git a/crates/algo/src/liquify/tests.rs b/crates/algo/src/liquify/tests.rs index 1cc360b2c3..80cc8dae2e 100644 --- a/crates/algo/src/liquify/tests.rs +++ b/crates/algo/src/liquify/tests.rs @@ -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> { + 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"); +} diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index daf7a2526a..c91a2611de 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -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 { + 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 { + 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 { 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 { @@ -780,10 +830,13 @@ pub fn tone_range(px: &[[f32; 4]], lo: f32, hi: f32, falloff: f32) -> Vec { 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; diff --git a/crates/algo/src/selection/tests.rs b/crates/algo/src/selection/tests.rs index 4e7bdcbe06..5f02b53a58 100644 --- a/crates/algo/src/selection/tests.rs +++ b/crates/algo/src/selection/tests.rs @@ -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)); } diff --git a/crates/algo/src/selection/wand_antialias_tests.rs b/crates/algo/src/selection/wand_antialias_tests.rs new file mode 100644 index 0000000000..6d435e12cf --- /dev/null +++ b/crates/algo/src/selection/wand_antialias_tests.rs @@ -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"); +} diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index b1f7bacaae..5a46b472e9 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -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 diff --git a/crates/compose/src/extents.rs b/crates/compose/src/extents.rs index c0ae28d340..d111ab8b57 100644 --- a/crates/compose/src/extents.rs +++ b/crates/compose/src/extents.rs @@ -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 { 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 { 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 { 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 { +/// 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 { 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 { + 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 { + 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 { + 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> { + 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 { + 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 diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e93e0818f3..5bc5e723ae 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -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}; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 153b038adf..5278fe1828 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -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) -> 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] diff --git a/crates/engine/src/brush_clear_background_tests.rs b/crates/engine/src/brush_clear_background_tests.rs new file mode 100644 index 0000000000..e295e68c0b --- /dev/null +++ b/crates/engine/src/brush_clear_background_tests.rs @@ -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 = 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:?}"); +} diff --git a/crates/engine/src/canvas_geom.rs b/crates/engine/src/canvas_geom.rs index 93bc4654b9..ff40ea8a8b 100644 --- a/crates/engine/src/canvas_geom.rs +++ b/crates/engine/src/canvas_geom.rs @@ -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 { diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4addf4c22..c727a8850d 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -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) -> 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 { 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 { // 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 { 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()); diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index 6a18a871f1..ed5da88e7d 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -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}"); diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index d9d7d1510c..ee51e9e2d0 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -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(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(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 { 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 { 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 { 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 { fn count_move(s: &mut Session, p: &Value) -> Result { 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 { fn count_new_group(s: &mut Session, p: &Value) -> Result { 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 { } 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 { 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> = Vec::new(); @@ -1297,8 +1382,8 @@ pub fn specs() -> Vec { "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 { ] } +#[cfg(test)] +#[path = "analysis_straighten_enabled_tests.rs"] +mod analysis_straighten_enabled_tests; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/analysis_cmds/tests.rs b/crates/engine/src/cmd/analysis_cmds/tests.rs index dc76470bc9..6978b4d059 100644 --- a/crates/engine/src/cmd/analysis_cmds/tests.rs +++ b/crates/engine/src/cmd/analysis_cmds/tests.rs @@ -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); diff --git a/crates/engine/src/cmd/analysis_straighten_enabled_tests.rs b/crates/engine/src/cmd/analysis_straighten_enabled_tests.rs new file mode 100644 index 0000000000..b2d107d7bb --- /dev/null +++ b/crates/engine/src/cmd/analysis_straighten_enabled_tests.rs @@ -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 { + 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]); +} diff --git a/crates/engine/src/cmd/artboard_cmds.rs b/crates/engine/src/cmd/artboard_cmds.rs index 91391edc25..00b0f7e37f 100644 --- a/crates/engine/src/cmd/artboard_cmds.rs +++ b/crates/engine/src/cmd/artboard_cmds.rs @@ -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 = 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 = 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 { 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 { 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 { } 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 { // 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 { 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 { )); } }; - 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 { 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 { 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 { 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()]})) } diff --git a/crates/engine/src/cmd/artboard_cmds/tests.rs b/crates/engine/src/cmd/artboard_cmds/tests.rs index e079c5b54c..356e87975d 100644 --- a/crates/engine/src/cmd/artboard_cmds/tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/tests.rs @@ -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. diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 0e90e5d3dc..e4bd93fb44 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -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; diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 162bf22f8a..31a6a6402d 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -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", diff --git a/crates/engine/src/cmd/atn_cmds/measurement_tests.rs b/crates/engine/src/cmd/atn_cmds/measurement_tests.rs new file mode 100644 index 0000000000..61fb0770be --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/measurement_tests.rs @@ -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) -> (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 { + 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")))); +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index c331d1c585..63a5c831eb 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -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 { 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")), diff --git a/crates/engine/src/cmd/atn_cmds/steps_measurement.rs b/crates/engine/src/cmd/atn_cmds/steps_measurement.rs new file mode 100644 index 0000000000..9669e7ad2b --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_measurement.rs @@ -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 { + 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 { + 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 { + 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))) +} diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 27b6f6500b..1c8a2911d8 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -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(); diff --git a/crates/engine/src/cmd/background_eraser_transparency_lock_tests.rs b/crates/engine/src/cmd/background_eraser_transparency_lock_tests.rs new file mode 100644 index 0000000000..a5993caa64 --- /dev/null +++ b/crates/engine/src/cmd/background_eraser_transparency_lock_tests.rs @@ -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 { + 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]); +} diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 61a35e5150..87a4bcdd41 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -832,6 +832,21 @@ fn mixer_load_pixel(s: &mut Session, p: &Value) -> Result { /// 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 { 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 { ), 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 { #[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; diff --git a/crates/engine/src/cmd/brush_cmds/mixer_live.rs b/crates/engine/src/cmd/brush_cmds/mixer_live.rs index bfe409c471..f0abb81995 100644 --- a/crates/engine/src/cmd/brush_cmds/mixer_live.rs +++ b/crates/engine/src/cmd/brush_cmds/mixer_live.rs @@ -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)> { + 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 { + 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)); diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index c7c7942d0b..9fd1762c45 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -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 { 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 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 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) { + 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); +} diff --git a/crates/engine/src/cmd/color_replacement_modes_tests.rs b/crates/engine/src/cmd/color_replacement_modes_tests.rs new file mode 100644 index 0000000000..b9c454fb33 --- /dev/null +++ b/crates/engine/src/cmd/color_replacement_modes_tests.rs @@ -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 { + 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"); + } +} diff --git a/crates/engine/src/cmd/count_history_names_tests.rs b/crates/engine/src/cmd/count_history_names_tests.rs new file mode 100644 index 0000000000..2cfa357ab4 --- /dev/null +++ b/crates/engine/src/cmd/count_history_names_tests.rs @@ -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"); + } +} diff --git a/crates/engine/src/cmd/count_record_label_tests.rs b/crates/engine/src/cmd/count_record_label_tests.rs new file mode 100644 index 0000000000..3b49b2dd38 --- /dev/null +++ b/crates/engine/src/cmd/count_record_label_tests.rs @@ -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}"); +} diff --git a/crates/engine/src/cmd/distort_cmds.rs b/crates/engine/src/cmd/distort_cmds.rs index 6eb7949c57..1b71aed4a0 100644 --- a/crates/engine/src/cmd/distort_cmds.rs +++ b/crates/engine/src/cmd/distort_cmds.rs @@ -435,7 +435,7 @@ fn perspective(s: &mut Session, p: &Value, cmd: &str) -> Result { } pub fn specs() -> Vec { - 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![ diff --git a/crates/engine/src/cmd/edit_cmds.rs b/crates/engine/src/cmd/edit_cmds.rs index dbf1a9a6f1..d460524c25 100644 --- a/crates/engine/src/cmd/edit_cmds.rs +++ b/crates/engine/src/cmd/edit_cmds.rs @@ -1267,8 +1267,8 @@ pub fn specs() -> Vec { 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")), diff --git a/crates/engine/src/cmd/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs index bf08c18ac2..8e2b16b41e 100644 --- a/crates/engine/src/cmd/eraser_cmds.rs +++ b/crates/engine/src/cmd/eraser_cmds.rs @@ -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 { 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 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 { ] } +#[cfg(test)] +mod magic_eraser_tolerance_tests; #[cfg(test)] mod tests; +#[cfg(test)] +#[path = "background_eraser_transparency_lock_tests.rs"] +mod transparency_lock_tests; diff --git a/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs b/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs new file mode 100644 index 0000000000..4369282590 --- /dev/null +++ b/crates/engine/src/cmd/eraser_cmds/magic_eraser_tolerance_tests.rs @@ -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"); + } +} diff --git a/crates/engine/src/cmd/eraser_cmds/tests.rs b/crates/engine/src/cmd/eraser_cmds/tests.rs index 07866aa72f..fd965b62e8 100644 --- a/crates/engine/src/cmd/eraser_cmds/tests.rs +++ b/crates/engine/src/cmd/eraser_cmds/tests.rs @@ -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()); diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index da5bc746b4..a4b0b8777f 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -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 { - 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 { 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 { }) } -/// Filter › Blur › Average: the selection (or layer) filled with its mean colour. -fn average(s: &mut Session, p: &Value) -> Result { - 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 { 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 { 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 { has_layer, show_only ), - spec!("filter.blur.average", "Average", &["Filter", "Blur"], None, "{}", has_pixels, average), ] } diff --git a/crates/engine/src/cmd/extra_cmds/tests.rs b/crates/engine/src/cmd/extra_cmds/tests.rs index 3543a012b4..ba0140504e 100644 --- a/crates/engine/src/cmd/extra_cmds/tests.rs +++ b/crates/engine/src/cmd/extra_cmds/tests.rs @@ -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); diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 495f9d1892..b1ec4df7d6 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -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 { 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 "-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::*; diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index 6121180e22..282eae0e4e 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -74,9 +74,15 @@ fn import_result(name: &str, bytes: &[u8]) -> Result Result { +pub(super) fn import_result_with(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result { + 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 ---------- diff --git a/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs b/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs new file mode 100644 index 0000000000..57bd8ce39f --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/open_as_smart_object.rs @@ -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 { + 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>, + r: photocraft_io::ImportResult, + pixels: photocraft_raster::Surface, + damaged: bool, +) -> Result { + 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); + // "-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 +} diff --git a/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs b/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs new file mode 100644 index 0000000000..c205af3d71 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/open_as_smart_object_tests.rs @@ -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 = (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 { + 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>) { + 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}"); +} diff --git a/crates/engine/src/cmd/file_cmds/raw_open.rs b/crates/engine/src/cmd/file_cmds/raw_open.rs index 905f359aaa..c252acc1de 100644 --- a/crates/engine/src/cmd/file_cmds/raw_open.rs +++ b/crates/engine/src/cmd/file_cmds/raw_open.rs @@ -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); + /// 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> { +fn prior_settings(path: Option<&str>) -> Result> { 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> { 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> { +fn prior_settings(path: Option<&str>) -> Result> { 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); diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index d42d333128..33b1f60875 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -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); diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 39c0b4acc6..9eff784a42 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -1256,7 +1256,7 @@ pub fn specs() -> Vec { "image.mode.rgb", "RGB Color", ["Image", "Mode"], - r##"{"profile":"|working|/path/to/profile.icc"=working,"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true}"##, + r##"{"profile":"|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) ), diff --git a/crates/engine/src/cmd/layer_css_cmds.rs b/crates/engine/src/cmd/layer_css_cmds.rs new file mode 100644 index 0000000000..d63fcb3263 --- /dev/null +++ b/crates/engine/src/cmd/layer_css_cmds.rs @@ -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) -> 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::>(); + 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 { + 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 { + 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 = 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 { + 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::>()})) +} + +/// 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, 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 { + 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; diff --git a/crates/engine/src/cmd/layer_css_cmds/tests.rs b/crates/engine/src/cmd/layer_css_cmds/tests.rs new file mode 100644 index 0000000000..368b965874 --- /dev/null +++ b/crates/engine/src/cmd/layer_css_cmds/tests.rs @@ -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::().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); +} diff --git a/crates/engine/src/cmd/layer_mask_props_cmds/tests.rs b/crates/engine/src/cmd/layer_mask_props_cmds/tests.rs index cd32de150f..572990d60f 100644 --- a/crates/engine/src/cmd/layer_mask_props_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_mask_props_cmds/tests.rs @@ -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(); diff --git a/crates/engine/src/cmd/layer_multi_cmds.rs b/crates/engine/src/cmd/layer_multi_cmds.rs index 5076d665ff..e17a258ba4 100644 --- a/crates/engine/src/cmd/layer_multi_cmds.rs +++ b/crates/engine/src/cmd/layer_multi_cmds.rs @@ -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; diff --git a/crates/engine/src/cmd/layer_multi_cmds/damage.rs b/crates/engine/src/cmd/layer_multi_cmds/damage.rs index a3fb64f032..2b77acd211 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/damage.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/damage.rs @@ -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 { 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 { 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 { 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 { 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 { || (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 { } } 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> { + 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 = ys.iter().map(|l| l.id).collect(); + let cx: Vec = xs.iter().map(|l| l.id).filter(|id| in_y.contains(id)).collect(); + let in_x: HashSet = cx.iter().copied().collect(); + let cy: Vec = 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 { 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 { - 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 { 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 { + 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 diff --git a/crates/engine/src/cmd/layer_multi_cmds/moves.rs b/crates/engine/src/cmd/layer_multi_cmds/moves.rs index 078dde4d57..b5f1edda37 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/moves.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/moves.rs @@ -152,6 +152,7 @@ pub fn translate(s: &mut Session, p: &Value) -> Result { } 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, Vec) = 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 { } // 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 { } Ok(nested) })?; + crate::artboard_cmds::follow_shift(s, shift); if nested.is_empty() { return Ok(Value::Null); } diff --git a/crates/engine/src/cmd/layer_multi_cmds/structure.rs b/crates/engine/src/cmd/layer_multi_cmds/structure.rs index 66974e1dd2..16cc828c81 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/structure.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/structure.rs @@ -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::>(); reselect(s, copies, active); Ok(json!({"layers": out, "layer": active.map(|l| l.0)})) diff --git a/crates/engine/src/cmd/layer_multi_cmds/tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tests.rs index fc39d25f5d..47ab7917d3 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/tests.rs @@ -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![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![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![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] diff --git a/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs index af70e8c9fe..5f1e880d79 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs @@ -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, 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"); + } +} diff --git a/crates/engine/src/cmd/lens_cmds.rs b/crates/engine/src/cmd/lens_cmds.rs index 1192281744..82376d65a6 100644 --- a/crates/engine/src/cmd/lens_cmds.rs +++ b/crates/engine/src/cmd/lens_cmds.rs @@ -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 { 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 { 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 { #[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 { diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index ea6504f7a8..2adde91685 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -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 { }) } +/// 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> { + 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 { 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 { }; 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 { "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], diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index 8f190f445c..e5dc8aac33 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -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. diff --git a/crates/engine/src/cmd/notes_cmds.rs b/crates/engine/src/cmd/notes_cmds.rs index 2f589f3390..e5530e17aa 100644 --- a/crates/engine/src/cmd/notes_cmds.rs +++ b/crates/engine/src/cmd/notes_cmds.rs @@ -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(at: &chrono::DateTime) -> 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> { 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 { 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 { fn delete(s: &mut Session, p: &Value) -> Result { 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); diff --git a/crates/engine/src/cmd/notes_stored_values_tests.rs b/crates/engine/src/cmd/notes_stored_values_tests.rs new file mode 100644 index 0000000000..1db8e5681b --- /dev/null +++ b/crates/engine/src/cmd/notes_stored_values_tests.rs @@ -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]); +} diff --git a/crates/engine/src/cmd/perspective_crop_cmds.rs b/crates/engine/src/cmd/perspective_crop_cmds.rs index fbff5c6e22..f1cc5f3165 100644 --- a/crates/engine/src/cmd/perspective_crop_cmds.rs +++ b/crates/engine/src/cmd/perspective_crop_cmds.rs @@ -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> { 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 { 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 { 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 { 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::*; diff --git a/crates/engine/src/cmd/perspective_crop_size_tests.rs b/crates/engine/src/cmd/perspective_crop_size_tests.rs new file mode 100644 index 0000000000..4fb25b8903 --- /dev/null +++ b/crates/engine/src/cmd/perspective_crop_size_tests.rs @@ -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"); +} diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 0746ca7440..115b8c40f9 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -260,7 +260,7 @@ pub fn specs() -> Vec { 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 { #[cfg(test)] mod tests; + +#[cfg(test)] +mod patch_history_names_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs index 6a8a6e2b05..66cf276332 100644 --- a/crates/engine/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -130,26 +130,19 @@ pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result { 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`. diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index e51ac10021..a950ad5992 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -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 diff --git a/crates/engine/src/cmd/retouch_cmds/heal.rs b/crates/engine/src/cmd/retouch_cmds/heal.rs index a260443caf..b26decfd69 100644 --- a/crates/engine/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine/src/cmd/retouch_cmds/heal.rs @@ -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 { 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 = 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)) diff --git a/crates/engine/src/cmd/retouch_cmds/patch.rs b/crates/engine/src/cmd/retouch_cmds/patch.rs index 1cfcd3bfca..1f1c6b023e 100644 --- a/crates/engine/src/cmd/retouch_cmds/patch.rs +++ b/crates/engine/src/cmd/retouch_cmds/patch.rs @@ -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 { 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 { /// docs), as a background job. fn patch_content_aware(s: &mut Session, p: &Value) -> Result { 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 { } }, 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 { }, ) } + +#[cfg(test)] +#[path = "patch_destination_selection_tests.rs"] +mod patch_destination_selection_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/patch_destination_selection_tests.rs b/crates/engine/src/cmd/retouch_cmds/patch_destination_selection_tests.rs new file mode 100644 index 0000000000..7ed9e54efa --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/patch_destination_selection_tests.rs @@ -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"); +} diff --git a/crates/engine/src/cmd/retouch_cmds/patch_history_names_tests.rs b/crates/engine/src/cmd/retouch_cmds/patch_history_names_tests.rs new file mode 100644 index 0000000000..2fcee6e1d7 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/patch_history_names_tests.rs @@ -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 { + 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:?}"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/periodic.rs b/crates/engine/src/cmd/retouch_cmds/periodic.rs index 242579198e..63c3b40f07 100644 --- a/crates/engine/src/cmd/retouch_cmds/periodic.rs +++ b/crates/engine/src/cmd/retouch_cmds/periodic.rs @@ -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 { 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, +) -> Result { + 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; diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 25ebcc8a97..f1980bae0d 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -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::>()).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"); + } +} diff --git a/crates/engine/src/cmd/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs index 13737e70bd..619a1af7ae 100644 --- a/crates/engine/src/cmd/selection_cmds.rs +++ b/crates/engine/src/cmd/selection_cmds.rs @@ -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 { 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 { 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 { @@ -756,7 +787,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/selection_cmds/wand_seed_outside_tests.rs b/crates/engine/src/cmd/selection_cmds/wand_seed_outside_tests.rs new file mode 100644 index 0000000000..51540e3cfd --- /dev/null +++ b/crates/engine/src/cmd/selection_cmds/wand_seed_outside_tests.rs @@ -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::>(), [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::>(), [true, true, false, false], "the fill stops at 0.49"); +} diff --git a/crates/engine/src/cmd/transform_cmds/multi_tests.rs b/crates/engine/src/cmd/transform_cmds/multi_tests.rs index a50e4239fd..ec0c817b12 100644 --- a/crates/engine/src/cmd/transform_cmds/multi_tests.rs +++ b/crates/engine/src/cmd/transform_cmds/multi_tests.rs @@ -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"); diff --git a/crates/engine/src/cmd/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs index d05c05f46a..f1f8aa53c4 100644 --- a/crates/engine/src/cmd/type_cmds.rs +++ b/crates/engine/src/cmd/type_cmds.rs @@ -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 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 { @@ -953,7 +1003,7 @@ pub fn specs() -> Vec { 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); diff --git a/crates/engine/src/cmd/type_indexed_mode_tests.rs b/crates/engine/src/cmd/type_indexed_mode_tests.rs new file mode 100644 index 0000000000..8f6a8058fb --- /dev/null +++ b/crates/engine/src/cmd/type_indexed_mode_tests.rs @@ -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 { + 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 { + 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 { + 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, ¶graph), "{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"); + } +} diff --git a/crates/engine/src/cmd/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs index e54c38fd19..df9d951520 100644 --- a/crates/engine/src/cmd/vector_cmds/paths.rs +++ b/crates/engine/src/cmd/vector_cmds/paths.rs @@ -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()] })) } diff --git a/crates/engine/src/cmd/warp_cmds.rs b/crates/engine/src/cmd/warp_cmds.rs index 4b94af82a9..f7d51eb4bf 100644 --- a/crates/engine/src/cmd/warp_cmds.rs +++ b/crates/engine/src/cmd/warp_cmds.rs @@ -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 { 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 { - 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 { + 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 { + 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 diff --git a/crates/engine/src/cmd/warp_cmds/tests.rs b/crates/engine/src/cmd/warp_cmds/tests.rs index 08130688c6..044014488c 100644 --- a/crates/engine/src/cmd/warp_cmds/tests.rs +++ b/crates/engine/src/cmd/warp_cmds/tests.rs @@ -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] { diff --git a/crates/engine/src/color_channels.rs b/crates/engine/src/color_channels.rs index c19c7e389c..97a1c90a26 100644 --- a/crates/engine/src/color_channels.rs +++ b/crates/engine/src/color_channels.rs @@ -123,7 +123,7 @@ pub(crate) fn refusal(s: &Session, id: &str, p: &Value) -> Option { 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 } diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index cb9bc5fe8a..5137fa8bac 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -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, + /// `(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, /// 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) { diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index d2fcd10064..7c9e28a64d 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -84,6 +84,7 @@ pub fn params_for(id: &str, p: &Value) -> Option { 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 { 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"], "{}"), diff --git a/crates/engine/src/filters/validation.rs b/crates/engine/src/filters/validation.rs index da816353d5..c658dd01ac 100644 --- a/crates/engine/src/filters/validation.rs +++ b/crates/engine/src/filters/validation.rs @@ -94,7 +94,8 @@ fn fields(id: &str) -> Option<&'static [(&'static str, Rule)]> { ("vertical", Number(f64::MIN, f64::MAX)), ("undefinedAreas", Choice("wrap|repeat|transparent")), ], - "filter.blur.blur" + "filter.blur.average" + | "filter.blur.blur" | "filter.blur.blurMore" | "filter.sharpen.sharpen" | "filter.sharpen.sharpenMore" diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 7c4419ea33..38459ef154 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -1790,7 +1790,7 @@ impl Session { // action it plays (a script step) must not flush the steps it ran so far into the action // being recorded, nor move the recording mark past the entries it is about to replace. let recording = if spec.journal && crate::actions_cmds::replayable(id) { self.actions.recording.take() } else { None }; - let before = self.active().map(|st| st.doc.clone()); + let before = self.active().map(|st| (st.doc.clone(), st.revision)); let docs_before: Vec<_> = self.docs.iter().map(|st| st.doc.id).collect(); // Last-resort guard (AGENTS.md, Never crash): a command that panics anyway fails with an // error instead of taking the app down. `edit` only commits a document after its closure @@ -1811,6 +1811,11 @@ impl Session { self.hint_before = None; } let pending = self.jobs.pending.take(); + if pending.is_none() + && let Some((doc, revision)) = &before + { + self.note_command_damage(id, doc, *revision); + } // Shape Blur by an installed shape's id or name records the geometry it ran with, as the // filter's own prepared params carry it: the journal (Last Filter, recorded actions) // replays where that shape is not installed. The run resolved it already, so it can't fail. @@ -1837,7 +1842,7 @@ impl Session { Ok(Started::Job(jid)) } (Ok(v), None) => { - if let Some(before) = &before { + if let Some((before, _)) = &before { self.add_relayout_damage(before); } if let Some((doc_id, layer_id)) = new_fx_target @@ -1866,6 +1871,29 @@ impl Session { out } + /// The one place a command's redraw area spans more than one revision. A command that moved + /// the active document's revision more than once (Paste Into, Stroke Path, a compound, a + /// script) reports what changed since it began, [`layer_multi_cmds::step_damage`] of the + /// document before and after, measured from the revision before it. A single-revision command + /// keeps the damage it reported. Debug and test builds also count a whole-document redraw of + /// a small change ([`Session::whole_redraws`]). + pub(crate) fn note_command_damage(&mut self, id: &str, before: &Arc, from: u64) { + let Some(st) = self.active_mut().filter(|st| st.doc.id == before.id && st.revision > from) else { return }; + if st.revision - from > 1 { + st.last_damage = crate::layer_multi_cmds::step_damage(before, &st.doc); + st.damage_span = Some((from, st.revision)); + } + #[cfg(any(test, debug_assertions))] + if st.last_damage.is_none() + && let Some(pct) = crate::layer_multi_cmds::small_change_pct(before, &st.doc) + { + eprintln!("warning: {id}: redraws the whole document but changed {pct}% of it"); + self.whole_redraws += 1; + } + #[cfg(not(any(test, debug_assertions)))] + let _ = id; + } + /// Grows the damage a command reported for the pixels it changed by what effects laid out /// over a layer's frame repaint when it moved ([`photocraft_compose::relayout_damage`]): a /// stroke on a layer with a Gradient Overlay reports the stroke, but the gradient is laid out @@ -2156,7 +2184,7 @@ mod tests; #[cfg(test)] #[path = "../../io/tests/support/recovery_psd.rs"] -mod psd_open_fixture; +pub(crate) mod psd_open_fixture; #[cfg(test)] mod psd_open_confirmation_tests { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8f28147217..bce1b26aaa 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -110,6 +110,7 @@ pub use cmd::history_select_cmds; pub use cmd::history_source_cmds; pub use cmd::image_cmds; pub use cmd::layer_copy_cmds; +pub use cmd::layer_css_cmds; pub use cmd::layer_label_cmds; pub use cmd::layer_list_cmds; pub use cmd::layer_mask_props_cmds; @@ -337,6 +338,9 @@ pub struct Session { /// command reporting too narrow a redraw area (#4053). Counted in debug and test builds only; /// tests read it. pub damage_misses: usize, + /// Commands that left the whole document to redraw (`last_damage` None) while changing under + /// 25 % of it ([`Session::dispatch`]). Counted in debug and test builds only; tests read it. + pub whole_redraws: usize, } #[cfg(test)] @@ -346,6 +350,8 @@ mod embed_all_linked_tests; #[cfg(test)] mod fill_layer_mode_tests; #[cfg(test)] +mod mixer_indexed_bitmap_tests; +#[cfg(test)] mod pattern_mode_tests; #[cfg(test)] mod second_keys_zoom_actions_tests; @@ -355,4 +361,6 @@ mod tests; #[cfg(test)] mod fx_mode_tests; +#[cfg(test)] +mod brush_clear_background_tests; pub mod command_hints; diff --git a/crates/engine/src/mixer_indexed_bitmap_tests.rs b/crates/engine/src/mixer_indexed_bitmap_tests.rs new file mode 100644 index 0000000000..8f31a41cd5 --- /dev/null +++ b/crates/engine/src/mixer_indexed_bitmap_tests.rs @@ -0,0 +1,60 @@ +//! The Mixer Brush refuses Indexed Color and Bitmap documents with the reference's alert texts +//! (#11958): `paint.mixerBrush` returns the error and leaves the document and History unchanged. +//! RGB, CMYK, Lab and Grayscale documents still paint. + +use crate::Session; +use crate::brush_cmds::mixer_live::{BITMAP_REFUSAL, INDEXED_REFUSAL}; +use serde_json::json; + +fn stroke(s: &mut Session) -> crate::Result { + s.execute("paint.mixerBrush", json!({"points": [[10, 10], [40, 20]], "size": 12, "wet": 0, "mix": 0})) +} + +fn assert_refused(s: &mut Session, text: &str) { + let (doc, steps) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.past_len()); + let err = stroke(s).unwrap_err().to_string(); + assert_eq!(err, text); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "nothing painted"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "no history step"); +} + +#[test] +fn indexed_color_documents_are_refused_with_the_alert() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + assert_refused(&mut s, INDEXED_REFUSAL); + assert_eq!( + INDEXED_REFUSAL, + "Could not use the Mixer Brush tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)." + ); +} + +#[test] +fn bitmap_documents_are_refused_with_the_alert() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 32, "background": "white"})).unwrap(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + s.execute("image.mode.bitmap", json!({})).unwrap(); + assert_refused(&mut s, BITMAP_REFUSAL); + assert_eq!(BITMAP_REFUSAL, "Could not use the Mixer Brush tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."); +} + +#[test] +fn rgb_cmyk_lab_and_grayscale_documents_still_paint() { + let mut painted = 0; + for mode in ["rgb", "cmyk", "lab", "grayscale"] { + for depth in [8, 16, 32] { + let mut s = Session::new(); + // Not every mode has every depth (as in the reference, CMYK and Lab stop at 16 bits). + if s.execute("file.new", json!({"width": 64, "height": 32, "mode": mode, "depth": depth, "background": "white"})).is_err() { + continue; + } + let steps = s.active().unwrap().history.past_len(); + stroke(&mut s).unwrap_or_else(|e| panic!("{mode} {depth}: {e}")); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{mode} {depth}"); + painted += 1; + } + } + assert!(painted >= 8, "only {painted} mode/depth combinations painted"); +} diff --git a/crates/engine/src/prefs/cmds.rs b/crates/engine/src/prefs/cmds.rs index fa695e1e92..0d34b8fbcd 100644 --- a/crates/engine/src/prefs/cmds.rs +++ b/crates/engine/src/prefs/cmds.rs @@ -180,7 +180,7 @@ pub fn specs() -> Vec { section!("edit.preferences.plugIns", "Plugins…"), section!("edit.preferences.type", "Type…"), section!("edit.preferences.enhancedControls", "Enhanced Controls…"), - section!("edit.preferences.rawDefaults", "Camera Raw…"), + section!("edit.preferences.rawDefaults", "RAW Defaults…"), section!("edit.preferences.integrations", "Integrations…"), spec!( "edit.keyboardShortcuts", diff --git a/crates/engine/src/prefs/validate.rs b/crates/engine/src/prefs/validate.rs index f9c0b9f805..ccbf2cd6ba 100644 --- a/crates/engine/src/prefs/validate.rs +++ b/crates/engine/src/prefs/validate.rs @@ -24,7 +24,7 @@ pub const SECTIONS: [(&str, &str); 18] = [ ("plugIns", "Plugins"), ("type", "Type"), ("enhancedControls", "Enhanced Controls"), - ("rawDefaults", "Camera Raw Defaults"), + ("rawDefaults", "RAW Defaults"), ("integrations", "Integrations"), ]; diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 49f8205079..b5b82a4753 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -193,6 +193,11 @@ impl Session { self.next_held_open } + /// Whether a document held back for its prompt already has `name`. + pub(crate) fn held_open_named(&self, name: &str) -> bool { + self.held_opens.iter().any(|(_, d, _)| d.name == name) + } + /// Takes a document a background open held back for the profile prompt: the document and /// whether its source is read-only. `None` when there is no such document (already taken). pub fn take_held_open(&mut self, id: u64) -> Option<(Document, bool)> { diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 5522f5fc5c..6263a9fe64 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -354,8 +354,10 @@ impl Session { /// A command's own rect for the pixels its latest [`Session::edit`] changed: sub-tile precise /// for a brush dab, where the edit's own damage ([`layer_multi_cmds::step_damage`]) has tile /// precision. The redraw area becomes the intersection of the two, so a hint can only narrow - /// it (or bound a change `step_damage` can't). In debug and test builds, a hint that misses a - /// tile the edit changed is counted in [`Session::damage_misses`] and logged; it never panics. + /// it (or bound a change `step_damage` can't). The hint is first grown as `step_damage` grows + /// a change (by a mask's feather and by effects, `grow_hint`), so the intersection keeps a + /// dab's soft ring and shadow. In debug and test builds, a hint that misses a tile the edit + /// changed is counted in [`Session::damage_misses`] and logged; it never panics. pub fn hint_damage(&mut self, rect: photocraft_geom::Rect) { #[cfg(any(test, debug_assertions))] if let Some(before) = self.hint_before.take() @@ -370,6 +372,7 @@ impl Session { } } let Some(st) = self.active_mut() else { return }; + let rect = layer_multi_cmds::grow_hint(&st.doc, rect); st.last_damage = Some(st.last_damage.map_or(rect, |d| d.intersect(&rect))); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8f82376a3a..25df001fea 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -966,6 +966,27 @@ fn command_list_filter_finds_the_marquees_by_keyword() { assert!(found("no command is called this").is_empty()); } +/// The rename to "RAW Develop" is display only: the filter and RAW Defaults are still found by +/// Photoshop's "Camera Raw" name, which their keywords carry (#12403). +#[test] +fn command_list_filter_finds_the_raw_commands_by_their_photoshop_name() { + let mut s = Session::new(); + let list = s.execute("command.list", json!({})).unwrap(); + let rows = list.as_array().unwrap(); + let found = |needle: &str| -> Vec { + rows.iter().filter(|c| crate::commands::list_entry_matches(c, needle)).map(|c| c["id"].as_str().unwrap().to_string()).collect() + }; + for needle in ["camera raw", "Camera Raw", "CAMERA RAW"] { + let ids = found(needle); + assert!(ids.contains(&"filter.cameraRaw".to_string()), "{needle}: {ids:?}"); + assert!(ids.contains(&"edit.preferences.rawDefaults".to_string()), "{needle}: {ids:?}"); + } + // What the menus show is the new name, and the keywords are not a label. + let label = |id: &str| rows.iter().find(|c| c["id"] == id).unwrap()["label"].as_str().unwrap().to_string(); + assert_eq!(label("filter.cameraRaw"), "RAW Develop Filter…"); + assert_eq!(label("edit.preferences.rawDefaults"), "RAW Defaults…"); +} + /// Every keyword entry names a real command, so a renamed id can't leave one behind. #[test] fn search_keywords_name_real_commands() { diff --git a/crates/engine/tests/it/average_smart.rs b/crates/engine/tests/it/average_smart.rs new file mode 100644 index 0000000000..0f6458f5f1 --- /dev/null +++ b/crates/engine/tests/it/average_smart.rs @@ -0,0 +1,124 @@ +//! Exercise Average through the smart-filter renderer, not an imported cache. +use photocraft_doc::LayerContent; +use photocraft_engine::{Session, filters, smart_cmds}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::json; + +fn image(s: &Session) -> Surface { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + match &l.content { + LayerContent::Raster(r) => r.clone(), + LayerContent::Smart(sm) => sm.cache.clone().unwrap(), + _ => panic!("expected pixels"), + } +} + +fn input(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let d = s.active_mut().unwrap(); + let l = std::sync::Arc::make_mut(&mut d.doc).layer_mut(d.active_layer.unwrap()).unwrap(); + let surf = l.surface_mut().unwrap(); + for y in 0..16 { + for x in 0..16 { + surf.write_region(Rect::new(x, y, x + 1, y + 1), if x < 8 { &[1.0, 0.0, 0.0, 1.0] } else { &[0.0, 0.0, 1.0, 1.0] }); + } + } + s +} + +fn purple(surf: &Surface) { + for p in surf.read_region(Rect::new(0, 0, 16, 16)).as_chunks::<4>().0 { + assert!((p[0] - 0.5).abs() <= 1.0 / 255.0, "{p:?}"); + assert_eq!(p[1], 0.0); + assert!((p[2] - 0.5).abs() <= 1.0 / 255.0, "{p:?}"); + assert_eq!(p[3], 1.0); + } +} + +#[test] +fn average_stored_filter_executes() { + for depth in [8, 16, 32] { + let s = input(depth); + let bounds = s.active().unwrap().doc.bounds(); + let out = filters::apply_filter_to_surface("filter.blur.average", &json!({}), &image(&s), bounds, None, bounds) + .unwrap() + .expect("Average must be executable, not treated as an unknown filter"); + purple(&out); + } +} + +#[test] +fn average_smart_command_rerenders_and_undoes() { + for depth in [8, 16, 32] { + let mut s = input(depth); + s.execute("filter.convertForSmartFilters", json!({})).unwrap(); + let before = image(&s); + let steps = s.active().unwrap().history.past_len(); + assert!(s.is_enabled("filter.blur.average")); + s.execute("filter.blur.average", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + purple(&image(&s)); + assert!(s.undo()); + assert_eq!(image(&s), before); + assert!(s.redo()); + purple(&image(&s)); + s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": false})).unwrap(); + assert_eq!(image(&s), before); + s.execute("layer.smartFilter.setVisible", json!({"index": 0, "visible": true})).unwrap(); + let d = s.active_mut().unwrap(); + let snapshot = d.doc.clone(); + let layer = std::sync::Arc::make_mut(&mut d.doc).layer_mut(d.active_layer.unwrap()).unwrap(); + if let LayerContent::Smart(sm) = &mut layer.content { + assert_eq!(sm.smart_filters.len(), 1); + assert_eq!(sm.smart_filters[0].command, "filter.blur.average"); + sm.cache = None; + } + smart_cmds::purge_stack_cache(); + assert!(smart_cmds::refresh_layer(&snapshot, layer).unwrap()); + purple(&image(&s)); + } +} + +#[test] +fn average_rejects_bad_params_without_an_edit() { + let mut s = input(8); + let before = image(&s); + let steps = s.active().unwrap().history.past_len(); + for params in [json!("bad"), json!({"unknown": 1}), json!({"layer": -1}), json!({"target": false})] { + assert!(s.execute("filter.blur.average", params).is_err()); + assert_eq!(image(&s), before); + assert_eq!(s.active().unwrap().history.past_len(), steps); + } +} + +/// Optional local oracle: generate a 16×16 red/blue Smart Object in Photoshop, apply Average, +/// save as PSD, then set PHOTOCRAFT_AVERAGE_PSD to that file. Never accept cached pixels as proof. +#[test] +#[ignore = "requires a locally generated Photoshop Average PSD; see docs/average-filter.md"] +fn average_photoshop_psd_rerenders_from_source() { + let path = std::env::var("PHOTOCRAFT_AVERAGE_PSD").expect("set PHOTOCRAFT_AVERAGE_PSD"); + let bytes = std::fs::read(&path).unwrap(); + let mut doc = photocraft_io::import(&path, &bytes).unwrap().document; + let snapshot = doc.clone(); + let ids: Vec<_> = snapshot + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Smart(sm) if sm.smart_filters.iter().any(|f| f.command == "filter.blur.average") => Some(l.id), + _ => None, + }) + .collect(); + assert_eq!(ids.len(), 1); + let layer = doc.layer_mut(ids[0]).unwrap(); + if let LayerContent::Smart(sm) = &mut layer.content { + sm.cache = None; + } + smart_cmds::purge_stack_cache(); + assert!(smart_cmds::refresh_layer(&snapshot, layer).unwrap()); + let LayerContent::Smart(sm) = &layer.content else { panic!("expected smart object") }; + purple(sm.cache.as_ref().unwrap()); +} diff --git a/crates/engine/tests/it/gradient_overlay_strokes.rs b/crates/engine/tests/it/gradient_overlay_strokes.rs index e233f8984d..304e34a834 100644 --- a/crates/engine/tests/it/gradient_overlay_strokes.rs +++ b/crates/engine/tests/it/gradient_overlay_strokes.rs @@ -67,7 +67,8 @@ fn a_gradient_overlay_is_laid_out_again_after_each_stroke() { fn a_stroke_inside_the_layer_keeps_its_own_damage() { let mut s = session("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})); s.execute("paint.stroke", json!({"points": [[10, 10], [150, 70]], "size": 12, "hardness": 1.0, "color": GREY})).unwrap(); - // Within the layer's bounds: the gradient's frame stays, so only the stroke repaints. + // Within the layer's bounds: the gradient's frame stays, so only the stroke repaints (grown + // by the effects' margin, as any change to the layer's pixels is). let r = s.execute("paint.stroke", json!({"points": [[60, 40], [70, 40]], "size": 6, "hardness": 1.0, "color": GREY})).unwrap(); let d = &r["damage"]; let reported = photocraft_geom::Rect::new( @@ -76,7 +77,9 @@ fn a_stroke_inside_the_layer_keeps_its_own_damage() { (d[0].as_i64().unwrap() + d[2].as_i64().unwrap()) as i32, (d[1].as_i64().unwrap() + d[3].as_i64().unwrap()) as i32, ); - assert_eq!(s.active().unwrap().last_damage, Some(reported)); + let st = s.active().unwrap(); + let margin = photocraft_compose::effects::margin(st.doc.layer(st.active_layer.unwrap()).unwrap()); + assert_eq!(st.last_damage, Some(reported.inflate(margin))); } #[test] diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index b53745ab2e..33e9e9e7cf 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -28,6 +28,7 @@ mod atn_stroke_width; mod atn_type_path; mod atn_v12; mod atn_video_frames; +mod average_smart; mod background_and_mask_depth; mod background_layer_consistency; mod brush_smoothing; diff --git a/crates/engine/tests/multi_channel_editing.rs b/crates/engine/tests/multi_channel_editing.rs index 5780c1318e..09cf6edc97 100644 --- a/crates/engine/tests/multi_channel_editing.rs +++ b/crates/engine/tests/multi_channel_editing.rs @@ -99,6 +99,12 @@ fn adjustments_filters_and_drawing_preserve_other_encoded_components() { let mut s = setup(mode, depth); subset(&mut s); let before = surface(&s); + // Color Replacement refuses 32-bit RGB, as the reference application does (#11923). + if *cmd == "paint.colorReplacement" && mode == "rgb" && depth == 32 { + assert!(s.execute(cmd, p.clone()).is_err(), "{mode} {depth} {cmd} is refused"); + assert_eq!(surface(&s), before, "{mode} {depth} {cmd}: nothing changed"); + continue; + } s.execute(cmd, p.clone()).unwrap_or_else(|e| panic!("{mode} {depth} {cmd}: {e}")); let after = surface(&s); unchanged(&before, &after); @@ -669,7 +675,8 @@ fn last_filter_rejects_non_object_journal_params_without_panicking() { #[test] fn first_single_channel_retouch_preview_preserves_every_other_sample() { for cmd in ["paint.dodge", "paint.burn", "paint.sponge", "paint.blur", "paint.sharpen", "paint.smudge", "paint.colorReplacement"] { - let mut s = setup("rgb", 32); + // Color Replacement refuses 32-bit RGB (#11923): it is checked at 16 bits. + let mut s = setup("rgb", if cmd == "paint.colorReplacement" { 16 } else { 32 }); s.execute("channel.target", json!({"channel":{"color":0}})).unwrap(); let before = surface(&s); let p = json!({"points":[[6,7,1],[23,15,0.7]],"size":9,"color":"#ffffff","tolerance":100}); @@ -765,7 +772,11 @@ fn lab_single_channel_tone_parameters_round_trip_without_applying_lightness_twic } fn flat_rgb() -> Session { - let mut s = setup("rgb", 32); + flat_rgb_at(32) +} + +fn flat_rgb_at(depth: u32) -> Session { + let mut s = setup("rgb", depth); s.edit("flat", |doc, id| { doc.layer_mut(id.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 32, 24), &[0.25, 0.5, 0.25, 1.0]); Ok(()) @@ -894,7 +905,8 @@ fn rgb_component_exposure_uses_the_document_transfer_at_all_depths() { #[test] fn color_replacement_live_preview_forwards_explicit_component_and_pixel_targets() { for target in [json!({"colors":[1]}), json!("pixels")] { - let mut s = flat_rgb(); + // 16-bit: Color Replacement refuses 32-bit RGB (#11923). + let mut s = flat_rgb_at(16); subset(&mut s); let params = json!({"points":[[8,8],[22,12]],"size":9,"tolerance":100,"mode":"luminosity","color":"#ffffff","seed":42,"target":target}); let live = photocraft_engine::brush_cmds::live_color_replacement(&s, ¶ms).unwrap(); diff --git a/crates/geom/src/warp.rs b/crates/geom/src/warp.rs index 8c1320cf6a..e6bf592606 100644 --- a/crates/geom/src/warp.rs +++ b/crates/geom/src/warp.rs @@ -67,8 +67,9 @@ impl WarpStyle { WarpStyle::Twist, ]; - /// The styles the Warp menus list: none, custom and the presets. [`WarpStyle::Cylinder`] is - /// read from PSDs and taken by commands, but has no editor yet. + /// The styles every Warp menu lists: none, custom and the presets. [`WarpStyle::Cylinder`] is + /// not one of them: Transform Warp's menu adds it after these (it has its own editor there), + /// while Warp Text has no cylinder. pub fn all() -> impl Iterator { [WarpStyle::None, WarpStyle::Custom].into_iter().chain(Self::PRESETS) } diff --git a/crates/gpu/src/camera_raw.rs b/crates/gpu/src/camera_raw.rs index 3f1833a54b..14f8a17e6c 100644 --- a/crates/gpu/src/camera_raw.rs +++ b/crates/gpu/src/camera_raw.rs @@ -75,7 +75,7 @@ impl CameraRawDevelop { pub fn new(device: &wgpu::Device) -> Result { match crate::first_error(device, || Self::build(device)) { (dev, None) => Ok(dev), - (_, Some(e)) => Err(Unsupported(format!("couldn't build the Camera Raw pipeline: {e}"))), + (_, Some(e)) => Err(Unsupported(format!("couldn't build the RAW Develop pipeline: {e}"))), } } @@ -246,7 +246,7 @@ impl CameraRawDevelop { Some(e) => { // A half-done upload must not be taken for the cached source next time. self.source = None; - Err(Unsupported(format!("GPU Camera Raw develop failed: {e}"))) + Err(Unsupported(format!("GPU RAW Develop failed: {e}"))) } None => result, } @@ -270,7 +270,7 @@ impl CameraRawDevelop { let bytes = u64::from(row) * u64::from(h); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_camera_raw") }); self.encode(device, queue, &mut encoder, source, key, size, stages)?; - let Some(target) = self.target.as_ref().map(|t| &t.texture) else { return Err(Unsupported("no Camera Raw target".into())) }; + let Some(target) = self.target.as_ref().map(|t| &t.texture) else { return Err(Unsupported("no RAW Develop target".into())) }; let buffer = match self.readback.take() { Some(b) if b.size() == bytes => b, _ => device.create_buffer(&wgpu::BufferDescriptor { @@ -316,10 +316,10 @@ impl CameraRawDevelop { fn check_size(device: &wgpu::Device, source: &[[f32; 4]], [w, h]: [u32; 2]) -> Result<(), Unsupported> { let max = device.limits().max_texture_dimension_2d; if w == 0 || h == 0 || w > max || h > max { - return Err(Unsupported(format!("a {w}×{h} Camera Raw preview doesn't fit the GPU's {max} px textures"))); + return Err(Unsupported(format!("a {w}×{h} RAW Develop preview doesn't fit the GPU's {max} px textures"))); } if source.len() as u64 != u64::from(w) * u64::from(h) { - return Err(Unsupported(format!("{} Camera Raw preview pixels for {w}×{h}", source.len()))); + return Err(Unsupported(format!("{} RAW Develop preview pixels for {w}×{h}", source.len()))); } Ok(()) } diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 36975e57eb..2090bdb00f 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -16,6 +16,9 @@ corpus = [] heif = ["photocraft-codecs/heif"] # Test support for synthetic memory injection, estimate charges and verification across crates. testgen = [] +# Editable PDF import (experimental): painted paths and embedded-font text become editable +# layers; unsupported constructs keep the raster page. +pdf-editable = ["dep:kurbo"] [dependencies] photocraft-geom = { workspace = true } @@ -53,6 +56,9 @@ resvg = { version = "0.45", default-features = false, features = ["text", "syste ttf-parser = { version = "0.25", default-features = false } # PDF import (pdf_import.rs): craft-pdf rasterizes pages in pure Rust; no shared library ships. craft-pdf = { workspace = true } +# Editable PDF import (pdf_editable.rs): craft-pdf's Device trait uses kurbo paths and transforms. +# This is the same kurbo 0.13 that craft-pdf already links; naming it adds no crate to the graph. +kurbo = { version = "0.13", optional = true } [target.'cfg(target_arch = "wasm32")'.dependencies] resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] } diff --git a/crates/io/src/camera_raw_xmp.rs b/crates/io/src/camera_raw_xmp.rs index 65df97e898..76fd8bb0ca 100644 --- a/crates/io/src/camera_raw_xmp.rs +++ b/crates/io/src/camera_raw_xmp.rs @@ -12,6 +12,13 @@ //! `IncrementalTemperature` / `IncrementalTint` (−100..=100), which are PhotoCraft's Temperature //! and Tint. The absolute `Temperature` (kelvin) / `Tint` of raw-file settings have no //! counterpart and are ignored. +//! +//! Crop (#9985): `crs:HasCrop="True"` with `crs:CropTop` / `CropLeft` / `CropBottom` / +//! `CropRight`, fractions of the developed frame in the raw's stored orientation (before its +//! Orientation tag turns it upright), is read into [`LoadReport::crop`]; the raw open crops the +//! document with it ([`crate::raw::RawTuning::crop`]). The settings have no crop (Camera Raw +//! Filter has none). Without `HasCrop`, or with `HasCrop="False"`, the crop keys are stale and +//! mean nothing. A straightened crop (`CropAngle` other than 0) isn't applied. use photocraft_algo::camera_raw::{CameraRaw, validate_curve}; @@ -126,7 +133,6 @@ const METADATA: &[&str] = &[ "Version", "ProcessVersion", "HasSettings", - "HasCrop", "WhiteBalance", "ToneCurveName2012", "CameraProfile", @@ -147,16 +153,114 @@ const METADATA: &[&str] = &[ "SortName", "Group", "Description", + // The raw file the sidecar belongs to (Lightroom and Camera Raw name it). + "RawFileName", ]; +/// The crop's keys besides `HasCrop`, and their values without a crop (the whole frame, level). +pub const CROP_KEYS: [&str; 5] = ["CropTop", "CropLeft", "CropBottom", "CropRight", "CropAngle"]; +const NO_CROP: [f32; 5] = [0.0, 0.0, 1.0, 1.0, 0.0]; + +/// A Camera Raw crop: fractions of the developed frame in the raw's stored orientation, before +/// its Orientation tag turns it upright, with `0 <= left < right <= 1` and +/// `0 <= top < bottom <= 1`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Crop { + pub top: f32, + pub left: f32, + pub bottom: f32, + pub right: f32, +} + +impl Crop { + /// The crop of the frame turned upright by TIFF orientation `o` (1–8; anything else is 1), + /// as fractions of the upright frame: the corners map as the pixels do. + pub fn oriented(self, o: u16) -> Crop { + let map = |u: f32, v: f32| match o { + 2 => (1.0 - u, v), + 3 => (1.0 - u, 1.0 - v), + 4 => (u, 1.0 - v), + 5 => (v, u), + 6 => (1.0 - v, u), + 7 => (1.0 - v, 1.0 - u), + 8 => (v, 1.0 - u), + _ => (u, v), + }; + let (ax, ay) = map(self.left, self.top); + let (bx, by) = map(self.right, self.bottom); + Crop { top: ay.min(by), left: ax.min(bx), bottom: ay.max(by), right: ax.max(bx) } + } + + /// The crop on a `w × h` frame in pixels, `(x0, y0, x1, y1)` with `x1` and `y1` exclusive: + /// at least one pixel, inside the frame. `None` for an empty frame. + pub fn pixels(self, w: usize, h: usize) -> Option<(usize, usize, usize, usize)> { + let edge = |f: f32, n: usize| ((f64::from(f).clamp(0.0, 1.0) * n as f64).round() as usize).min(n); + let span = |a: f32, b: f32, n: usize| { + let lo = edge(a, n).min(n.checked_sub(1)?); + Some((lo, edge(b, n).max(lo + 1))) + }; + let (x0, x1) = span(self.left, self.right, w)?; + let (y0, y1) = span(self.top, self.bottom, h)?; + Some((x0, y0, x1, y1)) + } +} + /// What [`load`] applied. #[derive(Clone, Debug, Default, PartialEq)] pub struct LoadReport { - /// How many settings were applied. + /// How many settings were applied (a crop counts as one). pub applied: usize, /// `crs:` settings without a PhotoCraft control (set to something other than their neutral - /// value), or with an unusable value, in file order. + /// value), or with an unusable value, in file order; then the keys of a crop that isn't + /// applied (straightened, unreadable or empty). pub ignored: Vec, + /// The file's crop, when it has one that isn't the whole frame. The settings hold no crop, + /// so the caller applies it (a raw open crops the document) or reports it. + pub crop: Option, +} + +/// The crop keys as read, resolved by [`crop`] once the whole file is read. +#[derive(Default)] +struct CropFields { + has: Option, + values: [Option; 5], +} + +/// The file's crop from its keys: applied when `HasCrop` is `True` and the values make a level, +/// non-empty rectangle (fractions are clamped to 0..1); otherwise its keys are reported. +fn crop(fields: &CropFields, report: &mut LoadReport) { + match fields.has.as_deref().map(str::trim) { + // No crop: the other keys are what Camera Raw left from an earlier or reset crop. + None => return, + Some(v) if v.eq_ignore_ascii_case("false") => return, + Some(v) if v.eq_ignore_ascii_case("true") => {} + Some(_) => { + report.ignored.push("HasCrop".into()); + return; + } + } + let mut v = NO_CROP; + let mut usable = true; + for (slot, text) in v.iter_mut().zip(&fields.values) { + if let Some(text) = text { + match number(text) { + Some(n) => *slot = n, + None => usable = false, + } + } + } + let [top, left, bottom, right] = [v[0], v[1], v[2], v[3]].map(|f| f.clamp(0.0, 1.0)); + // A straightened crop's rectangle is measured on the rotated frame: not applied. + usable &= v[4] == 0.0 && top < bottom && left < right; + if !usable { + let present = CROP_KEYS.iter().zip(&fields.values).filter(|(_, t)| t.is_some()); + report.ignored.extend(present.map(|(k, _)| k.to_string())); + return; + } + if [top, left, bottom, right] != [0.0, 0.0, 1.0, 1.0] { + report.crop = Some(Crop { top, left, bottom, right }); + report.applied += 1; + } } fn number(s: &str) -> Option { @@ -197,8 +301,14 @@ fn neutral(name: &str, value: &str) -> bool { } } -fn apply(params: &mut CameraRaw, report: &mut LoadReport, name: &str, value: &str) { - if let Some((_, field, lo, hi)) = SCALARS.iter().find(|(n, ..)| *n == name) { +fn apply(params: &mut CameraRaw, report: &mut LoadReport, crop: &mut CropFields, name: &str, value: &str) { + if name == "HasCrop" { + crop.has = Some(value.to_string()); + } else if let Some(i) = CROP_KEYS.iter().position(|k| *k == name) { + if let Some(slot) = crop.values.get_mut(i) { + *slot = Some(value.to_string()); + } + } else if let Some((_, field, lo, hi)) = SCALARS.iter().find(|(n, ..)| *n == name) { match number(value) { Some(v) => { *field(params) = v.clamp(*lo, *hi); @@ -232,10 +342,11 @@ pub fn load(params: &mut CameraRaw, bytes: &[u8]) -> Result let mut next = params.clone(); let mut report = LoadReport::default(); let mut found = false; + let mut crop_fields = CropFields::default(); for desc in doc.descendants().filter(|n| n.is_element() && n.tag_name().namespace() == Some(RDF_NS) && n.tag_name().name() == "Description") { for a in desc.attributes().filter(|a| a.namespace() == Some(CRS_NS)) { found = true; - apply(&mut next, &mut report, a.name(), a.value()); + apply(&mut next, &mut report, &mut crop_fields, a.name(), a.value()); } for c in desc.children().filter(|c| c.is_element() && c.tag_name().namespace() == Some(CRS_NS)) { found = true; @@ -254,13 +365,14 @@ pub fn load(params: &mut CameraRaw, bytes: &[u8]) -> Result report.ignored.push(name.to_string()); } } else { - apply(&mut next, &mut report, name, c.text().unwrap_or("")); + apply(&mut next, &mut report, &mut crop_fields, name, c.text().unwrap_or("")); } } } if !found { return Err("no Camera Raw settings in the file".into()); } + crop(&crop_fields, &mut report); *params = next; Ok(report) } @@ -295,6 +407,11 @@ pub fn is_photocraft_xmp(bytes: &[u8]) -> bool { /// Write `params` as a Camera Raw settings file Photoshop's Load Settings… reads. pub fn save(params: &CameraRaw) -> String { + save_with_crop(params, None) +} + +/// [`save`] with a raw file's crop, so rewriting a sidecar keeps the crop it was opened with. +pub fn save_with_crop(params: &CameraRaw, crop: Option) -> String { let mut p = params.clone(); let wb = if p.temperature != 0.0 || p.tint != 0.0 { "Custom" } else { "As Shot" }; let mut out = String::from( @@ -315,6 +432,12 @@ pub fn save(params: &CameraRaw) -> String { } let style = STYLES.iter().find(|(_, s)| *s == p.vignette_style).map_or("1", |(n, _)| n); out.push_str(&format!(" crs:PostCropVignetteStyle=\"{}\"\n", escape(style))); + if let Some(c) = crop { + out.push_str(&format!( + " crs:HasCrop=\"True\"\n crs:CropTop=\"{:.6}\"\n crs:CropLeft=\"{:.6}\"\n crs:CropBottom=\"{:.6}\"\n crs:CropRight=\"{:.6}\"\n crs:CropAngle=\"0\"\n", + c.top, c.left, c.bottom, c.right + )); + } out.push_str(" crs:ToneCurveName2012=\"Custom\"\n crs:HasSettings=\"True\">\n"); for (name, field) in CURVES { let points = field(&mut p); @@ -433,7 +556,7 @@ mod tests { abc"#; let r = load(&mut p, xmp).unwrap(); assert_eq!((p.exposure, p.contrast, p.clarity), (-5.0, 40.0, 0.0)); - assert_eq!(r, LoadReport { applied: 1, ignored: vec!["Clarity2012".into()] }); + assert_eq!(r, LoadReport { applied: 1, ignored: vec!["Clarity2012".into()], crop: None }); } #[test] @@ -479,4 +602,111 @@ mod tests { assert!(!is_photocraft_xmp(other), "{}", String::from_utf8_lossy(other)); } } + + /// A settings file with the `crs:` attributes `attrs`. + fn with(attrs: &str) -> String { + format!( + "" + ) + } + + fn report(attrs: &str) -> LoadReport { + load(&mut CameraRaw::default(), with(attrs).as_bytes()).unwrap() + } + + /// #9985: Lightroom's sidecar named the crop's bottom and right edges and the raw's file name + /// as unsupported; the crop is read now, and the file name is bookkeeping. + #[test] + fn reads_the_crop_and_not_the_file_name() { + let r = report(r#"crs:HasCrop="True" crs:CropTop="0.1" crs:CropLeft="0.2" crs:CropBottom="0.9" crs:CropRight="0.75" crs:CropAngle="0""#); + assert!(r.ignored.is_empty(), "{:?}", r.ignored); + assert_eq!(r.crop, Some(Crop { top: 0.1, left: 0.2, bottom: 0.9, right: 0.75 })); + assert_eq!(r.applied, 1); + // Element form, and the keys spread over two descriptions, read the same. + let xmp = format!( + "True0.5" + ); + let r = load(&mut CameraRaw::default(), xmp.as_bytes()).unwrap(); + assert_eq!(r.crop, Some(Crop { top: 0.0, left: 0.0, bottom: 0.5, right: 0.5 }), "missing edges are the frame's"); + assert!(r.ignored.is_empty(), "{:?}", r.ignored); + } + + #[test] + fn no_crop_without_has_crop_true() { + let keys = r#"crs:CropTop="0.1" crs:CropLeft="0.2" crs:CropBottom="0.9" crs:CropRight="0.75" crs:CropAngle="3""#; + for has in ["", r#"crs:HasCrop="False""#, r#"crs:HasCrop="false""#] { + let r = report(&format!("{has} {keys}")); + assert_eq!((r.crop, r.ignored.clone(), r.applied), (None, Vec::new(), 0), "{has:?}: {r:?}"); + } + // The whole frame is no crop, and nothing to report. + let r = report(r#"crs:HasCrop="True" crs:CropTop="0" crs:CropLeft="0" crs:CropBottom="1" crs:CropRight="1" crs:CropAngle="0""#); + assert_eq!((r.crop, r.ignored.len()), (None, 0)); + let r = report(r#"crs:HasCrop="yes" crs:CropBottom="0.5""#); + assert_eq!((r.crop, r.ignored), (None, vec!["HasCrop".to_string()])); + } + + /// Hostile and straightened crops never panic: out-of-range fractions are clamped to the + /// frame; an inverted, empty, unreadable or straightened crop isn't applied and its keys are + /// named. + #[test] + fn unusable_crops_are_reported_not_applied() { + let r = report(r#"crs:HasCrop="True" crs:CropTop="-0.5" crs:CropLeft="0.25" crs:CropBottom="7" crs:CropRight="1.0000001""#); + assert_eq!(r.crop, Some(Crop { top: 0.0, left: 0.25, bottom: 1.0, right: 1.0 })); + assert!(r.ignored.is_empty(), "{:?}", r.ignored); + let all = || CROP_KEYS.iter().map(|k| k.to_string()).collect::>(); + for bad in [ + r#"crs:CropTop="0.8" crs:CropLeft="0.1" crs:CropBottom="0.2" crs:CropRight="0.9" crs:CropAngle="0""#, + r#"crs:CropTop="0.5" crs:CropLeft="0.1" crs:CropBottom="0.5" crs:CropRight="0.9" crs:CropAngle="0""#, + r#"crs:CropTop="2" crs:CropLeft="0.1" crs:CropBottom="3" crs:CropRight="0.9" crs:CropAngle="0""#, + r#"crs:CropTop="NaN" crs:CropLeft="0.1" crs:CropBottom="0.9" crs:CropRight="0.9" crs:CropAngle="0""#, + r#"crs:CropTop="0.1" crs:CropLeft="inf" crs:CropBottom="0.9" crs:CropRight="0.9" crs:CropAngle="0""#, + r#"crs:CropTop="0.1" crs:CropLeft="0.1" crs:CropBottom="0.9" crs:CropRight="" crs:CropAngle="0""#, + r#"crs:CropTop="0.1" crs:CropLeft="0.1" crs:CropBottom="0.9" crs:CropRight="0.9" crs:CropAngle="1.38""#, + r#"crs:CropTop="0.1" crs:CropLeft="0.1" crs:CropBottom="0.9" crs:CropRight="0.9" crs:CropAngle="NaN""#, + ] { + let r = report(&format!(r#"crs:HasCrop="True" {bad}"#)); + assert_eq!((r.crop, r.ignored, r.applied), (None, all(), 0), "{bad}"); + } + let r = report(r#"crs:HasCrop="True" crs:CropAngle="-2.5""#); + assert_eq!(r.ignored, vec!["CropAngle".to_string()], "only the keys the file has"); + } + + /// Corners map as `photocraft-raw`'s orientation maps pixels (`develop::source_xy`). + #[test] + fn crops_follow_the_orientation() { + let c = Crop { top: 0.1, left: 0.2, bottom: 0.6, right: 0.5 }; + let want = [ + (1, Crop { top: 0.1, left: 0.2, bottom: 0.6, right: 0.5 }), + (2, Crop { top: 0.1, left: 0.5, bottom: 0.6, right: 0.8 }), + (3, Crop { top: 0.4, left: 0.5, bottom: 0.9, right: 0.8 }), + (4, Crop { top: 0.4, left: 0.2, bottom: 0.9, right: 0.5 }), + (5, Crop { top: 0.2, left: 0.1, bottom: 0.5, right: 0.6 }), + (6, Crop { top: 0.2, left: 0.4, bottom: 0.5, right: 0.9 }), + (7, Crop { top: 0.5, left: 0.4, bottom: 0.8, right: 0.9 }), + (8, Crop { top: 0.5, left: 0.1, bottom: 0.8, right: 0.6 }), + (0, Crop { top: 0.1, left: 0.2, bottom: 0.6, right: 0.5 }), + ]; + for (o, w) in want { + let got = c.oriented(o); + let close = [got.top - w.top, got.left - w.left, got.bottom - w.bottom, got.right - w.right].iter().all(|d| d.abs() < 1e-6); + assert!(close, "orientation {o}: {got:?}"); + } + assert_eq!(c.pixels(10, 20), Some((2, 2, 5, 12))); + assert_eq!(Crop { top: 0.5, left: 0.5, bottom: 0.5001, right: 0.5001 }.pixels(10, 10), Some((5, 5, 6, 6)), "at least a pixel"); + assert_eq!(Crop { top: 0.999, left: 0.999, bottom: 1.0, right: 1.0 }.pixels(10, 10), Some((9, 9, 10, 10)), "inside the frame"); + assert_eq!(c.pixels(0, 10), None); + } + + #[test] + fn save_with_crop_round_trips() { + let p = CameraRaw { contrast: 20.0, ..CameraRaw::default() }; + let crop = Crop { top: 0.125, left: 0.25, bottom: 0.875, right: 0.5 }; + let text = save_with_crop(&p, Some(crop)); + assert!(is_photocraft_xmp(text.as_bytes())); + let mut back = CameraRaw::default(); + let r = load(&mut back, text.as_bytes()).unwrap(); + assert_eq!((back, r.crop), (p.clone(), Some(crop))); + assert!(r.ignored.is_empty(), "{:?}", r.ignored); + assert_eq!(load(&mut CameraRaw::default(), save(&p).as_bytes()).unwrap().crop, None); + } } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 195a58b01a..c796b7cffa 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -65,6 +65,8 @@ pub use ora::losses as ora_losses; pub mod pattern_map; mod pcraft_cache; pub mod pdf; +#[cfg(all(feature = "pdf-editable", not(target_arch = "wasm32")))] +mod pdf_editable; mod pdf_import; mod pdn; pub use pcraft_cache::PcraftExportCache; @@ -612,6 +614,13 @@ pub struct ImportOptions { pub pdf_dpi: f32, /// The 1-based, inclusive page range to import; `None` imports every page (up to the cap). pub pdf_pages: Option<(u32, u32)>, + /// Import PDF painted paths and embedded-font text as editable [`photocraft_doc::ShapeLayer`]s + /// and text layers instead of a page raster (experimental). Images, complex clips/masks, + /// patterns, non-normal blends and unembedded/Type 3 text make that page fall back to the + /// raster importer with a warning. Text that uses fonts embedded in the PDF may change font + /// when edited or reopened, because the document format does not carry the font bytes. Off by + /// default. + pub pdf_editable: bool, /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. pub psd_high_memory_approved: bool, /// Optional estimate limit for high-memory approval. When set, approval only applies if @@ -628,6 +637,7 @@ impl Default for ImportOptions { flat_max_pixel_bytes: 0, pdf_dpi: 300.0, pdf_pages: None, + pdf_editable: false, psd_high_memory_approved: false, psd_approved_estimate: None, } diff --git a/crates/io/src/pdf_editable.rs b/crates/io/src/pdf_editable.rs new file mode 100644 index 0000000000..af56f64e21 --- /dev/null +++ b/crates/io/src/pdf_editable.rs @@ -0,0 +1,1807 @@ +//! Experimental editable PDF import: a `craft-pdf` device turns painted paths into shape layers +//! and embedded-font text into text layers. +//! +//! Solid fills and strokes become [`ShapeLayer`]s in document pixels; embedded fonts whose glyphs +//! carry Unicode and a PostScript name become [`photocraft_doc::TextLayer`]s, with the font bytes +//! registered in the app's shared text engine. A page-sized axis-aligned clip that contains the +//! artboard is a no-op and is accepted. Images, other clipping paths, transparency groups, +//! patterns, soft masks, annotations and unsupported text mark the page unsupported, and the +//! caller falls back to the raster importer for that page with a warning. Nothing is ever half +//! imported. +//! +//! This is the app-owned `Device` route: Hayro's interpreter walks the page and reports each +//! paint with its real colour and geometry, so shape layers need no page raster underneath. That +//! is what makes moving or deleting a layer behave, and what avoids the black-path and +//! doubled-text failures of the old PDFium import. + +use std::collections::hash_map::DefaultHasher; +use std::collections::{HashMap, HashSet}; +use std::hash::{Hash, Hasher}; +use std::panic::AssertUnwindSafe; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::time::Duration; + +use craft_pdf::interpret::color::Color as HayroColor; +use craft_pdf::interpret::font::{FontData, Glyph, OutlineFontData}; +use craft_pdf::interpret::{ + BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, InterpreterWarning, Paint, PathDrawMode, SoftMask, + TransformExt, interpret_page, +}; +use craft_pdf::syntax::page::Page; +use kurbo::{Affine as KurboAffine, BezPath, Cap, Join, PathEl}; +use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; +use photocraft_doc::text::{CharStyle, TextRun}; +use photocraft_doc::vector::{FillRule, Knot, LineCap, LineJoin, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, Subpath}; +use photocraft_doc::{Fill, Layer, LayerContent, TextLayer}; +use photocraft_geom::{Affine, Point, Rect, TILE_SIZE}; +use photocraft_raster::Interrupt; + +/// Most layers one editable page may create; past it the page falls back to raster. +const MAX_LAYERS: usize = 20_000; +/// Most path knots one editable page may hold; past it the page falls back to raster. +const MAX_KNOTS: usize = 1_000_000; +/// Allocated tile bytes of all shape and text caches retained by one editable page. +const MAX_CACHE_BYTES: u64 = 256 << 20; +/// Bound text collection before building its layers and caches, including repeated overprinting. +const MAX_GLYPHS: usize = 100_000; +/// The strings in collected glyph records must also fit, not just their record count. +const MAX_GLYPH_BYTES: usize = 16 << 20; +/// Cap on fill/stroke glyph comparisons so hostile pages cannot make pairing quadratic forever. +const MAX_PAIR_CHECKS: usize = 1_000_000; +/// How often the watcher copies the interrupt into craft-pdf's cancellation flag. The Device's +/// callbacks are only reached per paint, so a page with one long path still needs this; 20 ms +/// keeps wakeups negligible while staying responsive. +const POLL: Duration = Duration::from_millis(20); +/// Largest gap (in em) inside one run before a space is inserted. +const WORD_GAP: f64 = 0.2; +/// Largest baseline offset (in em) for glyphs to share one line. +const LINE_TOLERANCE: f64 = 0.30; + +/// Why an editable page could not be built. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EditableError { + /// The caller cancelled the import. + Cancelled, + /// The page uses something this first step cannot represent; rasterise it instead. + Unsupported(&'static str), +} + +/// Builds one page's shape layers in document coordinates inside `rect`. +/// +/// `rect` is the page's artboard in document pixels; the page's displayed size comes from +/// `Page::render_dimensions()` (CropBox, rotation and UserUnit already applied), so a point maps +/// to `rect` by the per-axis scale `rect.size / render_dimensions`. Nothing here re-applies the +/// CropBox offset or rotation. +pub fn page(page: &Page<'_>, rect: Rect, ctl: &Interrupt) -> Result, EditableError> { + ctl.check().map_err(|_| EditableError::Cancelled)?; + let (width_pt, height_pt) = page.render_dimensions(); + if !width_pt.is_finite() || !height_pt.is_finite() || width_pt <= 0.0 || height_pt <= 0.0 { + return Err(EditableError::Unsupported("the page has no area")); + } + let sx = f64::from(rect.width()) / f64::from(width_pt); + let sy = f64::from(rect.height()) / f64::from(height_pt); + let doc = Affine::translate(f64::from(rect.x0), f64::from(rect.y0)).mul(&Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] }); + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); + let cancelled = Arc::new(AtomicBool::new(false)); + let finished = Arc::new(AtomicBool::new(false)); + let warned = Arc::new(AtomicU8::new(0)); + let sink = Arc::clone(&warned); + let settings = InterpreterSettings { + cancelled: Some(Arc::clone(&cancelled)), + warning_sink: Arc::new(move |warning| { + let bit = match warning { + InterpreterWarning::ImageDecodeFailure => 1, + InterpreterWarning::UnsupportedFont => 2, + InterpreterWarning::ContentTruncated => 4, + }; + sink.fetch_or(bit, Ordering::Relaxed); + }), + ..InterpreterSettings::default() + }; + let cache = InterpreterCache::new(); + let mut device = PathDevice { + doc, + clip: rect, + fmt, + dpi: 72.0 * sx, + ctl: *ctl, + layers: Vec::new(), + glyphs: Vec::new(), + glyph_bytes: 0, + strokes: Vec::new(), + fonts: Vec::new(), + font_keys: HashMap::new(), + seen_fonts: HashSet::new(), + soft_mask: false, + clips: Vec::new(), + knots: 0, + cached: 0, + unsupported: None, + cancelled: false, + }; + std::thread::scope(|scope| { + let flag = Arc::clone(&cancelled); + let done = Arc::clone(&finished); + let ctl = *ctl; + scope.spawn(move || { + while !done.load(Ordering::Relaxed) { + if ctl.cancelled() { + flag.store(true, Ordering::Relaxed); + } + std::thread::sleep(POLL); + } + }); + // A hostile page must not take the process down. This only guards profiles that unwind; + // a `panic = "abort"` build aborts here just as the raster path would. + let result = std::panic::catch_unwind(AssertUnwindSafe(|| { + let bbox = kurbo::Rect::new(0.0, 0.0, f64::from(width_pt), f64::from(height_pt)); + let mut context = Context::new(page.initial_transform(true).to_kurbo(), bbox, &cache, page.xref(), settings); + interpret_page(page, &mut context, &mut device); + })); + if result.is_err() { + device.unsupported = Some("the page could not be interpreted"); + } + finished.store(true, Ordering::Relaxed); + }); + if device.cancelled || ctl.cancelled() { + return Err(EditableError::Cancelled); + } + let warned = warned.load(Ordering::Relaxed); + if warned & 4 != 0 { + return Err(EditableError::Unsupported("the page content was truncated")); + } + if warned & 2 != 0 { + return Err(EditableError::Unsupported("a font could not be used")); + } + if warned & 1 != 0 { + return Err(EditableError::Unsupported("an image could not be decoded")); + } + if let Some(reason) = device.unsupported { + return Err(EditableError::Unsupported(reason)); + } + pair_fake_bold(&mut device.glyphs, device.strokes, ctl)?; + let families = register_fonts(&device.fonts)?; + let texts = text_layers(&device.glyphs, &families, device.dpi, ctl)?; + if device.layers.len().saturating_add(texts.len()) > MAX_LAYERS { + return Err(EditableError::Unsupported("too many objects")); + } + let mut layers = merge_text_layers(device.layers, texts); + render_text_caches(&mut layers, device.dpi, device.fmt, ctl, &mut device.cached)?; + Ok(layers) +} + +/// Removes stroked glyphs that duplicate a fill at the same place, marking that glyph fake bold. +fn pair_fake_bold(glyphs: &mut [GlyphRun], strokes: Vec, ctl: &Interrupt) -> Result<(), EditableError> { + // Index fills by the exact attributes a stroke must match, so each stroke only compares + // against candidates at its own paint order/font/text instead of the whole page. + let mut index: HashMap<(usize, u128, u64), Vec> = HashMap::new(); + for (at, glyph) in glyphs.iter().enumerate() { + if at.is_multiple_of(256) && ctl.check().is_err() { + return Err(EditableError::Cancelled); + } + index.entry((glyph.order, glyph.font.key, text_hash(&glyph.text))).or_default().push(at); + } + let mut paired = vec![false; glyphs.len()]; + let mut checks = 0usize; + for stroke in strokes { + let mut found = None; + if let Some(candidates) = index.get(&(stroke.order, stroke.font.key, text_hash(&stroke.text))) { + for &at in candidates { + if paired[at] { + continue; + } + if checks == MAX_PAIR_CHECKS { + return Err(EditableError::Unsupported("too much stroked text")); + } + if checks.is_multiple_of(256) && ctl.check().is_err() { + return Err(EditableError::Cancelled); + } + checks += 1; + let glyph = &glyphs[at]; + let tolerance = 0.01 * glyph.size_px + 0.01; + if glyph.text == stroke.text + && same_style(glyph, &stroke) + && (glyph.origin.x - stroke.origin.x).abs() <= tolerance + && (glyph.origin.y - stroke.origin.y).abs() <= tolerance + { + found = Some(at); + break; + } + } + } + let Some(at) = found else { + return Err(EditableError::Unsupported("stroked text")); + }; + glyphs[at].fake_bold = true; + paired[at] = true; + } + Ok(()) +} + +/// A hash of a glyph string for the fake-bold index; equality is still checked on the string. +fn text_hash(text: &str) -> u64 { + let mut hasher = DefaultHasher::new(); + text.hash(&mut hasher); + hasher.finish() +} + +/// Builds one point-text layer per line and style run, with the layer index it must be inserted +/// at to preserve paint order relative to paths. +fn text_layers( + glyphs: &[GlyphRun], + families: &std::collections::HashMap, + dpi: f64, + ctl: &Interrupt, +) -> Result, EditableError> { + let mut out = Vec::new(); + let mut i = 0; + while i < glyphs.len() { + ctl.check().map_err(|_| EditableError::Cancelled)?; + if out.len() >= MAX_LAYERS { + return Err(EditableError::Unsupported("too many text objects")); + } + let first = &glyphs[i]; + let family = families.get(&first.font.key).cloned().unwrap_or_else(|| first.font.family.clone()); + let (dx, dy) = (first.angle.cos(), first.angle.sin()); + let (nx, ny) = (-dy, dx); + let baseline = first.origin.x * nx + first.origin.y * ny; + let start = i; + let mut text = String::new(); + let mut positions = Vec::new(); + let mut last = first; + while i < glyphs.len() { + let glyph = &glyphs[i]; + if glyph.order != first.order || !same_style(glyph, first) { + break; + } + let line = glyph.origin.x * nx + glyph.origin.y * ny; + if (line - baseline).abs() > LINE_TOLERANCE * first.size_px { + break; + } + if i > start { + let along = (glyph.origin.x - first.origin.x) * dx + (glyph.origin.y - first.origin.y) * dy; + let prev = (last.origin.x - first.origin.x) * dx + (last.origin.y - first.origin.y) * dy; + let gap = along - (prev + last.advance); + if gap > 3.0 * first.size_px { + break; + } + if gap > WORD_GAP * first.size_px && !text.ends_with(' ') { + text.push(' '); + } + } + positions.push((text.len(), glyph.origin)); + text.push_str(&glyph.text); + last = glyph; + i += 1; + } + if !text.is_empty() && has_ink(&text) { + let layer = text_layer(text, first, out.len(), &family); + if let LayerContent::Text(text) = &layer.content { + let shared = photocraft_text::shared(); + let mut engine = shared.lock().unwrap_or_else(|error| error.into_inner()); + let layout = engine.layout(text, dpi as f32); + // PDF spacing is already in the glyph origins. A word-gap heuristic cannot + // preserve TJ, character spacing, or explicitly positioned glyphs. Keep a run + // editable only if the actual text layout reproduces every recorded origin. + let clusters: std::collections::HashMap<_, _> = layout.clusters.iter().map(|c| (c.range.start, c)).collect(); + for (offset, expected) in positions { + let cluster = clusters.get(&offset); + let actual = + cluster.and_then(|c| layout.lines.get(c.line).map(|line| text.transform.apply(Point::new(f64::from(c.x), f64::from(line.baseline))))); + if actual.is_none_or(|at| (at.x - expected.x).abs() > 0.5 || (at.y - expected.y).abs() > 0.5) { + return Err(EditableError::Unsupported("text positioning")); + } + } + } + out.push((first.order, layer)); + } + if i == start { + i += 1; + } + } + Ok(out) +} + +/// Whether `b` belongs to the same line and style run as `a`. +fn same_style(a: &GlyphRun, b: &GlyphRun) -> bool { + let weight = |glyph: &GlyphRun| if glyph.fake_bold { 700 } else { glyph.font.weight }; + a.font.key == b.font.key + && a.font.family == b.font.family + && a.font.italic == b.font.italic + && weight(a) == weight(b) + && (a.size_pt - b.size_pt).abs() < 0.05 + && (a.angle - b.angle).abs() < 0.02 + && (a.color.c[0] - b.color.c[0]).abs() < 0.004 + && (a.color.c[1] - b.color.c[1]).abs() < 0.004 + && (a.color.c[2] - b.color.c[2]).abs() < 0.004 + && (a.color.alpha - b.color.alpha).abs() < 0.004 +} + +/// One line's point-text layer, with the family the shared engine registered. +fn text_layer(text: String, run: &GlyphRun, number: usize, family: &str) -> Layer { + let weight = if run.fake_bold { 700 } else { run.font.weight }; + let font_style = match (weight >= 600, run.font.italic) { + (true, true) => "Bold Italic", + (true, false) => "Bold", + (false, true) => "Italic", + (false, false) => "Regular", + }; + let style = CharStyle { + font_family: family.to_string(), + font_style: font_style.to_string(), + postscript_name: Some(run.font.postscript.clone()), + weight: u16::try_from(weight).unwrap_or(400), + italic: run.font.italic, + faux_bold: run.fake_bold, + // PDF positions already contain kerning; applying font kerning again moves glyphs. + kerning: photocraft_doc::text::Kerning::Off, + size_pt: run.size_pt as f32, + color: run.color, + ..CharStyle::default() + }; + let layer = TextLayer { + text: text.clone(), + font_family: family.to_string(), + size_pt: run.size_pt as f32, + color: run.color, + transform: Affine::translate(run.origin.x, run.origin.y).mul(&Affine::rotate(run.angle)), + runs: vec![TextRun { len: text.len(), style }], + ..TextLayer::default() + }; + Layer::new(format!("Text {}", number + 1), LayerContent::Text(layer)) +} + +/// Registers each embedded face with the shared engine under its content-keyed family and returns +/// the family each font key must use. +fn register_fonts(fonts: &[(u128, String, String, FontData)]) -> Result, EditableError> { + let shared = photocraft_text::shared(); + let mut families = std::collections::HashMap::new(); + for (key, postscript, derived, data) in fonts { + // Copy before taking the engine lock; parsing still happens under it, but the UI's + // layout is not blocked while the bytes are cloned. + let bytes = data.as_ref().as_ref().to_vec(); + let mut engine = shared.lock().unwrap_or_else(|error| error.into_inner()); + // Prefer an installed full family; a subset only holds the glyphs the page uses. The + // Device has the font program's PostScript name, not the PDF `/BaseFont`; a content-keyed + // alias keeps two documents' subsets of one name apart for the life of the shared engine, + // and the same face imported twice reuses its registration. + let family = if engine.has_family(derived) { + derived.clone() + } else { + let alias = font_alias(postscript, *key); + if engine.has_family(&alias) { + alias + } else { + let names = engine.register_font_data_as(bytes, &alias); + if names.is_empty() && !engine.has_family(&alias) { + return Err(EditableError::Unsupported("a font could not be registered")); + } + names.first().cloned().unwrap_or(alias) + } + }; + families.insert(*key, family); + } + Ok(families) +} + +/// Renders the text caches so the page is complete before the engine refreshes it. +fn render_text_caches(layers: &mut [Layer], dpi: f64, fmt: PixelFormat, ctl: &Interrupt, cached: &mut u64) -> Result<(), EditableError> { + let shared = photocraft_text::shared(); + for layer in layers { + if ctl.check().is_err() { + return Err(EditableError::Cancelled); + } + if let LayerContent::Text(text) = &mut layer.content + && has_ink(&text.text) + { + // Re-lock per layer so a text-heavy import does not hold the UI's engine for the + // whole cache-render loop. + let mut engine = shared.lock().unwrap_or_else(|error| error.into_inner()); + let layout = engine.layout(text, dpi as f32); + let area = photocraft_text::render::ink_rect(&layout, &text.transform); + admit_cache(cached, area, fmt)?; + let rendered = photocraft_text::render::rasterize(&layout, &text.transform, fmt, text.antialias); + let rect = rendered.rect; + text.cache = Some(rendered.surface); + if rect.width() == 0 || rect.height() == 0 { + return Err(EditableError::Unsupported("a text cache could not be rendered")); + } + } + } + Ok(()) +} + +/// Reserves complete tiles before rendering: even one painted pixel allocates a whole tile. +fn admit_cache(cached: &mut u64, area: Rect, fmt: PixelFormat) -> Result<(), EditableError> { + let bytes = area.tile_count().saturating_mul(TILE_SIZE as u64).saturating_mul(TILE_SIZE as u64).saturating_mul(fmt.bytes_per_pixel() as u64); + let total = cached.saturating_add(bytes); + if total > MAX_CACHE_BYTES { + return Err(EditableError::Unsupported("page cache budget")); + } + *cached = total; + Ok(()) +} + +/// Puts text layers back at the path index where their glyphs were painted. +fn merge_text_layers(layers: Vec, mut texts: Vec<(usize, Layer)>) -> Vec { + texts.sort_by_key(|(order, _)| *order); + let mut out = Vec::with_capacity(layers.len() + texts.len()); + let mut texts = texts.into_iter().peekable(); + for (index, layer) in layers.into_iter().enumerate() { + while texts.peek().is_some_and(|(order, _)| *order <= index) { + if let Some((_, text)) = texts.next() { + out.push(text); + } + } + out.push(layer); + } + out.extend(texts.map(|(_, layer)| layer)); + out +} + +/// A content key for an embedded face, used to group its glyphs and to keep aliases unique. +fn font_content_key(data: &OutlineFontData) -> u128 { + let hash = blake3::hash(data.data.as_ref().as_ref()); + let mut key = [0u8; 16]; + key.copy_from_slice(&hash.as_bytes()[..16]); + u128::from_le_bytes(key) +} + +/// Whether text has a visible character (not only spaces, controls or zero-width marks). +fn has_ink(text: &str) -> bool { + text.chars().any(|c| !c.is_whitespace() && !c.is_control() && !matches!(c, '\u{200B}'..='\u{200F}' | '\u{2060}' | '\u{FEFF}')) +} + +/// The family alias an embedded face is registered under: its PostScript name plus a content +/// key, so subsets with the same name from different documents cannot replace each other. +fn font_alias(postscript: &str, key: u128) -> String { + format!("{postscript} {key:016x}") +} + +/// Collects filled and stroked paths and glyph runs; anything else marks the page unsupported. +struct PathDevice<'a> { + /// Page points to document pixels: translation to the artboard plus the per-axis scale. + doc: Affine, + /// The page's artboard in document pixels; shape caches and strokes are clipped to it. + clip: Rect, + /// Document pixel format the shape caches are rendered in. + fmt: PixelFormat, + /// Document DPI, for text-layer caches. + dpi: f64, + ctl: Interrupt<'a>, + layers: Vec, + /// Filled glyphs in content order. + glyphs: Vec, + glyph_bytes: usize, + /// Stroked glyphs, paired with a fill at the same place to recognise fake bold. + strokes: Vec, + /// Embedded fonts met on the page: cache key, PostScript name, derived family and bytes. + fonts: Vec<(u128, String, String, FontData)>, + /// Hayro's cheap font identity → our content hash, so bytes are hashed once per face. + font_keys: HashMap, + /// Content keys of fonts already in [`Self::fonts`], so glyph callbacks do not scan it. + seen_fonts: HashSet, + /// Whether a soft mask is active; the first paint under one falls back the page. + soft_mask: bool, + /// One entry per clip pushed by the interpreter: `true` for an accepted no-op clip. + clips: Vec, + knots: usize, + /// Allocated tile bytes of caches retained so far. + cached: u64, + unsupported: Option<&'static str>, + cancelled: bool, +} + +/// One drawn glyph with the style the text layer needs. +struct GlyphRun { + text: String, + /// Baseline origin in document pixels. + origin: Point, + size_pt: f64, + /// Em size in document pixels. + size_px: f64, + /// Baseline direction in radians (view space, y down). + angle: f64, + /// Advance in document pixels. + advance: f64, + font: FontInfo, + /// How many layers had been drawn when this glyph was painted; text runs split at a path + /// between glyphs so paint order is preserved. + order: usize, + color: Color, + /// Drawn both filled and stroked: word-processor fake bold. + fake_bold: bool, +} + +/// The font style a run carries. +#[derive(Clone)] +struct FontInfo { + /// Hayro's font cache key, to group glyphs of one font. + key: u128, + family: String, + postscript: String, + weight: u32, + italic: bool, +} + +impl PathDevice<'_> { + /// Stops collecting at the first thing this step cannot represent. + fn unsupported(&mut self, reason: &'static str) { + if self.unsupported.is_none() { + self.unsupported = Some(reason); + } + } + + /// Whether `clip` is an axis-aligned rectangle that contains the whole artboard, so it + /// changes nothing in document space and can be ignored. + fn no_op_clip(&self, clip: &ClipPath) -> bool { + let Some((x0, y0, x1, y1)) = axis_aligned_rect(&clip.path) else { return false }; + let a = self.doc.apply(Point::new(x0, y0)); + let b = self.doc.apply(Point::new(x1, y1)); + let (dx0, dx1) = (a.x.min(b.x), a.x.max(b.x)); + let (dy0, dy1) = (a.y.min(b.y), a.y.max(b.y)); + let board = self.clip; + dx0 <= f64::from(board.x0) + 0.5 && dy0 <= f64::from(board.y0) + 0.5 && dx1 >= f64::from(board.x1) - 0.5 && dy1 >= f64::from(board.y1) - 0.5 + } + + /// Adds one shape layer unless a page cap is reached. Renders its pixel cache within the + /// page's cache budget so the layer is visible before the engine refreshes it. + fn push_shape(&mut self, path: Path, fill: Option, stroke: Option) { + if self.ctl.check().is_err() { + self.cancelled = true; + return; + } + if path.is_empty() { + return; + } + if stroke.as_ref().is_some_and(|stroke| !stroke.dashes.is_empty()) && path.subpaths.iter().any(is_zero_length) { + // A dashed zero-length subpath cannot be reproduced as a single point. + self.unsupported("a dashed zero-length subpath"); + return; + } + if self.layers.len() >= MAX_LAYERS { + self.unsupported("too many objects"); + return; + } + let mut shape = ShapeLayer { path, fill, stroke, ..ShapeLayer::default() }; + // Use the renderer's actual ink bounds, including miter tips, and reuse the compilation. + // Control-point bounds expanded by one stroke width can clip acute joins. + let compiled = photocraft_vector::CompiledShape::new(&shape, photocraft_vector::DEFAULT_TOLERANCE, self.clip); + let area = compiled.bounds().unwrap_or(Rect::EMPTY).intersect(&self.clip); + if area.width() > 0 && area.height() > 0 { + if let Err(EditableError::Unsupported(reason)) = admit_cache(&mut self.cached, area, self.fmt) { + self.unsupported(reason); + return; + } + shape.cache = Some(compiled.render(self.fmt, area)); + } + self.layers.push(Layer::new(format!("Path {}", self.layers.len() + 1), LayerContent::Shape(shape))); + } +} + +impl<'a> Device<'a> for PathDevice<'_> { + /// A soft mask changes compositing in ways a plain layer cannot express, but it only matters + /// if something is painted while it is active. + fn set_soft_mask(&mut self, mask: Option>) { + self.soft_mask = mask.is_some(); + } + + /// Only normal blending is editable. + fn set_blend_mode(&mut self, blend_mode: BlendMode) { + if blend_mode != BlendMode::Normal { + self.unsupported("blend modes"); + } + } + + /// Turns a filled/stroked path into a shape layer, rejecting paints and strokes it cannot keep. + fn draw_path(&mut self, path: &BezPath, transform: KurboAffine, paint: &Paint<'a>, draw_mode: &PathDrawMode) { + if self.unsupported.is_some() { + return; + } + if self.soft_mask { + self.unsupported("soft masks"); + return; + } + if self.ctl.check().is_err() { + self.cancelled = true; + return; + } + let color = match paint { + Paint::Color(color) => to_color(color), + Paint::Pattern(_) => { + self.unsupported("patterns"); + return; + } + }; + let full = self.doc.mul(&knots_affine(&transform)); + let Some(path) = to_path(path, &full, &mut self.knots) else { + self.unsupported("too many path points"); + return; + }; + match draw_mode { + PathDrawMode::Fill(rule) => { + let mut path = path; + path.fill_rule = match rule { + craft_pdf::interpret::FillRule::NonZero => FillRule::NonZero, + craft_pdf::interpret::FillRule::EvenOdd => FillRule::EvenOdd, + }; + self.push_shape(path, Some(Fill::Solid(color)), None); + } + PathDrawMode::Stroke(stroke) => { + if !uniform_transform(&transform) { + self.unsupported("non-uniform stroke transform"); + return; + } + let Some(stroke) = to_stroke(stroke, color, full.determinant().abs().sqrt()) else { + self.unsupported("stroke properties"); + return; + }; + self.push_shape(path, None, Some(stroke)); + } + } + } + + /// Accepts an axis-aligned clip that contains the artboard; other clips fall back. + fn push_clip_path(&mut self, clip_path: &ClipPath) { + if self.no_op_clip(clip_path) { + self.clips.push(true); + return; + } + self.clips.push(false); + self.unsupported("clipping paths"); + } + + /// Transparency groups are not represented by the layer model. + fn push_transparency_group(&mut self, _opacity: f32, mask: Option>, blend_mode: BlendMode) { + // A group needs its own blend/opacity/mask handling; until that exists the page is + // rasterised rather than flattened into the wrong stacking order. + let _ = (mask, blend_mode); + self.unsupported("transparency groups"); + } + + /// Records a filled glyph as text, or its stroke copy for fake-bold pairing. + fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: KurboAffine, glyph_transform: KurboAffine, paint: &Paint<'a>, draw_mode: &GlyphDrawMode) { + if self.unsupported.is_some() { + return; + } + if matches!(draw_mode, GlyphDrawMode::Invisible) { + return; + } + if self.soft_mask { + self.unsupported("soft masks"); + return; + } + if self.ctl.check().is_err() { + self.cancelled = true; + return; + } + if matches!(draw_mode, GlyphDrawMode::Clip) { + self.unsupported("text used as a clipping path"); + return; + } + if self.glyphs.len().saturating_add(self.strokes.len()) >= MAX_GLYPHS { + self.unsupported("too many glyphs"); + return; + } + let text = match glyph.as_unicode() { + Some(craft_pdf::interpret::hayro_cmap::BfString::Char(c)) => c.to_string(), + Some(craft_pdf::interpret::hayro_cmap::BfString::String(s)) => s, + None => { + // No Unicode means the text layer could not be edited faithfully. + self.unsupported("text without a Unicode mapping"); + return; + } + }; + if text.is_empty() || text.chars().all(|c| c.is_control()) { + return; + } + let Glyph::Outline(outline) = glyph else { + self.unsupported("Type 3 text"); + return; + }; + let Some(data) = outline.font_data() else { + self.unsupported("text without an embedded font"); + return; + }; + if !data.embedded { + self.unsupported("text in a substituted font"); + return; + } + let Some(postscript) = data.postscript_name.clone().filter(|name| !name.is_empty()) else { + self.unsupported("text without a font name"); + return; + }; + let color = match paint { + Paint::Color(color) => to_color(color), + Paint::Pattern(_) => { + self.unsupported("text with a pattern paint"); + return; + } + }; + let t = transform * glyph_transform; + let [a, b, c, d, e, f] = t.as_coeffs(); + // A glyph space of 1000 units per em, so the determinant's square root is 1/1000 of the + // em size. Upright text has a positive a and a negative d (the view flips y). + let size_pt = (a * d - b * c).abs().sqrt() * 1000.0; + if !size_pt.is_finite() || size_pt <= 0.0 { + self.unsupported("text without a usable size"); + return; + } + // Skewed, mirrored or sheared text cannot be a point text layer; leave the page to raster. + // After the view's y flip an upright or rotated run has a ≈ -d and b ≈ c. + let tolerance = 0.01 * (a * d - b * c).abs().sqrt(); + if (a + d).abs() > tolerance || (b - c).abs() > tolerance { + self.unsupported("skewed or mirrored text"); + return; + } + if let GlyphDrawMode::Stroke(stroke) = draw_mode { + // Only a thin, solid, same-colour outline can be approximated by faux bold. + // Colour equality is checked against the fill in pair_fake_bold. + if !stroke.line_width.is_finite() + || stroke.line_width < 0.0 + || f64::from(stroke.line_width) * transform.determinant().abs().sqrt() > size_pt * 0.05 + || !stroke.dash_array.is_empty() + { + self.unsupported("stroked text geometry"); + return; + } + } + let origin = self.doc.apply(Point::new(e, f)); + let size_px = size_pt * self.doc.determinant().abs().sqrt(); + let angle = b.atan2(a); + if !angle.is_finite() || !size_px.is_finite() || size_px <= 0.0 { + self.unsupported("text without a usable transform"); + return; + } + let advance = f64::from(outline.advance_width().unwrap_or(500.0)) / 1000.0 * size_px; + let weight = font_weight(&data, &postscript); + let italic = data.is_italic || name_has(&postscript, &["italic", "oblique"]); + let identity = outline.font_cache_key(); + let key = *self.font_keys.entry(identity).or_insert_with(|| font_content_key(&data)); + let family = family_from_postscript(&postscript); + if self.seen_fonts.insert(key) { + self.fonts.push((key, postscript.clone(), family.clone(), data.data.clone())); + } + let bytes = std::mem::size_of::().saturating_add(text.len()).saturating_add(family.len()).saturating_add(postscript.len()); + self.glyph_bytes = self.glyph_bytes.saturating_add(bytes); + if self.glyph_bytes > MAX_GLYPH_BYTES { + self.unsupported("glyph memory budget"); + return; + } + let font = FontInfo { key, family, postscript, weight, italic }; + let glyph = GlyphRun { text, origin, size_pt, size_px, angle, advance, font, color, fake_bold: false, order: self.layers.len() }; + if matches!(draw_mode, GlyphDrawMode::Stroke(_)) { + self.strokes.push(glyph); + } else { + self.glyphs.push(glyph); + } + } + + /// Images are not editable at this step. + fn draw_image(&mut self, _image: Image<'a, '_>, _transform: KurboAffine) { + self.unsupported("images"); + } + + /// Balances [`Self::push_clip_path`]. + fn pop_clip_path(&mut self) { + let _ = self.clips.pop(); + } + + /// Balances [`Self::push_transparency_group`]. + fn pop_transparency_group(&mut self) {} + + /// Annotations are not part of the page's editable paint. + fn begin_annotations(&mut self) { + self.unsupported("annotations"); + } +} + +/// The weight a font is given to a text layer, from its metadata and name. +fn font_weight(data: &OutlineFontData, postscript: &str) -> u32 { + if name_has(postscript, &["bold", "semibold", "demibold", "extrabold", "ultrabold", "black", "heavy"]) { + return data.weight.unwrap_or(700).max(700); + } + data.weight.unwrap_or(400) +} + +/// Whether `name` contains any of the lowercase style words. +fn name_has(name: &str, words: &[&str]) -> bool { + let lower = name.to_ascii_lowercase(); + words.iter().any(|word| lower.contains(word)) +} + +/// A family name from a `/BaseFont`/PostScript name, per the rules PdfCraft and pdfcer use: +/// drop a six-letter subset tag, a trailing style suffix and `MT`/`PS`, then space camel case. +/// The raw name stays in `CharStyle::postscript_name`, because some systems match that spelling. +fn family_from_postscript(name: &str) -> String { + let mut s = name; + if s.len() > 7 && s.as_bytes()[6] == b'+' && s[..6].bytes().all(|b| b.is_ascii_uppercase()) { + s = &s[7..]; + } + if let Some((head, tail)) = s.rsplit_once('-') + && is_style_word(tail) + { + s = head; + } + loop { + if let Some(rest) = s.strip_suffix("PSMT") { + s = rest; + } else if let Some(rest) = s.strip_suffix("MT") { + s = rest; + } else if let Some(rest) = s.strip_suffix("PS") { + s = rest; + } else { + break; + } + } + let spaced = space_camel(s); + if spaced.is_empty() { name.to_string() } else { spaced } +} + +/// Whether a suffix is a style word (after dropping `MT`/`PS` from it). +fn is_style_word(word: &str) -> bool { + let mut w = word; + loop { + if let Some(rest) = w.strip_suffix("MT") { + w = rest; + } else if let Some(rest) = w.strip_suffix("PS") { + w = rest; + } else { + break; + } + } + matches!( + w.to_ascii_lowercase().as_str(), + "bold" + | "italic" + | "oblique" + | "bolditalic" + | "boldoblique" + | "regular" + | "medium" + | "light" + | "black" + | "semibold" + | "demibold" + | "heavy" + | "thin" + | "book" + | "roman" + | "condensed" + | "narrow" + | "extended" + ) +} + +/// `TimesNewRoman` → `Times New Roman`; acronym runs and hyphens stay as they are. +fn space_camel(name: &str) -> String { + let chars: Vec = name.chars().collect(); + let mut out = String::with_capacity(name.len() + 4); + for (i, ch) in chars.iter().copied().enumerate() { + let prev = i.checked_sub(1).and_then(|j| chars.get(j)).copied(); + let next = chars.get(i + 1).copied(); + let boundary = ch.is_ascii_uppercase() && prev.is_some_and(|p| p.is_ascii_lowercase() || p.is_ascii_digit()) + || ch.is_ascii_uppercase() && prev.is_some_and(|p| p.is_ascii_uppercase()) && next.is_some_and(|n| n.is_ascii_lowercase()); + if boundary && !out.is_empty() && !out.ends_with(' ') && !out.ends_with('-') { + out.push(' '); + } + out.push(ch); + } + out +} + +/// The bounds of a path that is one axis-aligned rectangle, else `None`. +fn axis_aligned_rect(path: &BezPath) -> Option<(f64, f64, f64, f64)> { + let elements = path.elements(); + if !(5..=6).contains(&elements.len()) { + return None; + } + let mut points = Vec::with_capacity(4); + for element in elements { + match *element { + PathEl::MoveTo(p) | PathEl::LineTo(p) => points.push((p.x, p.y)), + PathEl::ClosePath => {} + PathEl::QuadTo(..) | PathEl::CurveTo(..) => return None, + } + } + if points.len() != 4 { + // An explicitly closed rectangle uses four LineTo points plus the duplicate start. + if points.len() == 5 && (points[0].0 - points[4].0).abs() < 1.0e-6 && (points[0].1 - points[4].1).abs() < 1.0e-6 { + points.pop(); + } else { + return None; + } + } + let x0 = points.iter().map(|p| p.0).fold(f64::INFINITY, f64::min); + let x1 = points.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max); + let y0 = points.iter().map(|p| p.1).fold(f64::INFINITY, f64::min); + let y1 = points.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max); + if !(x1 > x0 && y1 > y0) { + return None; + } + let on_edge = |v: f64, lo: f64, hi: f64| (v - lo).abs() < 1.0e-6 || (v - hi).abs() < 1.0e-6; + if points.iter().any(|(x, y)| !on_edge(*x, x0, x1) || !on_edge(*y, y0, y1)) { + return None; + } + // A bow-tie traversal also visits the four corners, so require its shoelace area to match + // the bounding box (a real rectangle covers it exactly). + let mut twice_area = 0.0; + for i in 0..4 { + let (ax, ay) = points[i]; + let (bx, by) = points[(i + 1) % 4]; + twice_area += ax * by - bx * ay; + } + let box_area = (x1 - x0) * (y1 - y0); + if (twice_area.abs() * 0.5 - box_area).abs() > box_area * 1.0e-3 { + return None; + } + Some((x0, y0, x1, y1)) +} + +/// Whether every knot of a subpath shares the first anchor (a zero-length subpath). +fn is_zero_length(subpath: &Subpath) -> bool { + subpath.knots.first().is_some_and(|first| subpath.knots.iter().all(|knot| knot.anchor.x == first.anchor.x && knot.anchor.y == first.anchor.y)) +} + +/// Whether a path transform keeps circles circular: both axes the same length and perpendicular. +fn uniform_transform(transform: &KurboAffine) -> bool { + let [a, b, c, d, _, _] = transform.as_coeffs(); + let x = (a * a + b * b).sqrt(); + let y = (c * c + d * d).sqrt(); + if !x.is_finite() || !y.is_finite() || x <= 0.0 || y <= 0.0 { + return false; + } + let same = (x - y).abs() <= 0.01 * x.max(y); + let square = (a * c + b * d).abs() <= 0.01 * x * y; + same && square +} + +/// A PDF colour as a straight-alpha PhotoCraft colour. +fn to_color(color: &HayroColor) -> Color { + let rgba = color.to_rgba(); + // `AlphaColor` components are straight (not premultiplied), despite the raster path being + // premultiplied: `Color::to_rgba8` reads them as straight too. + let [r, g, b, a] = rgba.components(); + Color::rgba(r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0), a.clamp(0.0, 1.0)) +} + +/// A kurbo affine as PhotoCraft's affine (same `[a, b, c, d, e, f]` layout). +fn knots_affine(transform: &KurboAffine) -> Affine { + let [a, b, c, d, e, f] = transform.as_coeffs(); + Affine { m: [a, b, c, d, e, f] } +} + +/// A Hayro stroke as PhotoCraft's stroke: width in pixels, dashes in multiples of the width. +fn to_stroke(stroke: &craft_pdf::interpret::StrokeProps, color: Color, scale: f64) -> Option { + if !stroke.line_width.is_finite() || stroke.line_width < 0.0 || !scale.is_finite() || scale <= 0.0 { + return None; + } + // A zero line width is the thinnest line the device can draw (ISO 32000-2 §8.4.3.2); the + // raster path draws it one document pixel wide, so do the same and use that as the dash base. + let width = if stroke.line_width > 0.0 { stroke.line_width * scale as f32 } else { 1.0 }; + if !width.is_finite() || width <= 0.0 { + return None; + } + let mut dashes: Vec = stroke.dash_array.iter().map(|dash| dash * scale as f32 / width).collect(); + // An odd PDF dash array repeats, so [3] means 3 on, 3 off rather than a single entry. + if dashes.len() % 2 == 1 { + let copy = dashes.clone(); + dashes.extend(copy); + } + Some(ShapeStroke { + width, + paint: Fill::Solid(color), + opacity: 1.0, + align: StrokeAlign::Center, + cap: match stroke.line_cap { + Cap::Butt => LineCap::Butt, + Cap::Round => LineCap::Round, + Cap::Square => LineCap::Square, + }, + join: match stroke.line_join { + Join::Miter => LineJoin::Miter, + Join::Round => LineJoin::Round, + Join::Bevel => LineJoin::Bevel, + }, + miter_limit: stroke.miter_limit, + dashes, + dash_offset: stroke.dash_offset * scale as f32 / width, + }) +} + +/// Converts a kurbo path to PhotoCraft's cubic knot model. `None` once `knots` passes the cap. +fn to_path(bez: &BezPath, transform: &Affine, knots: &mut usize) -> Option { + let mut subpaths = Vec::new(); + let mut current: Option = None; + let mut restarted = false; + let mut last = Point::new(0.0, 0.0); + for element in bez.elements() { + match *element { + PathEl::MoveTo(p) => { + if let Some(subpath) = current.take() + && (!restarted || subpath.knots.len() > 1) + { + subpaths.push(subpath); + } + restarted = false; + current = Some(Subpath { closed: false, knots: vec![Knot::corner(p.x, p.y)], op: PathOp::Combine }); + last = Point::new(p.x, p.y); + } + PathEl::LineTo(p) => { + if let Some(subpath) = current.as_mut() { + if let Some(knot) = subpath.knots.last_mut() { + knot.out_ctrl = knot.anchor; + } + subpath.knots.push(Knot::corner(p.x, p.y)); + } + last = Point::new(p.x, p.y); + } + PathEl::QuadTo(control, p) => { + if let Some(subpath) = current.as_mut() { + let start = subpath.knots.last().map_or(last, |knot| knot.anchor); + if let Some(knot) = subpath.knots.last_mut() { + knot.out_ctrl = Point::new(start.x + 2.0 / 3.0 * (control.x - start.x), start.y + 2.0 / 3.0 * (control.y - start.y)); + } + subpath.knots.push(Knot { + anchor: Point::new(p.x, p.y), + in_ctrl: Point::new(p.x + 2.0 / 3.0 * (control.x - p.x), p.y + 2.0 / 3.0 * (control.y - p.y)), + out_ctrl: Point::new(p.x, p.y), + smooth: false, + }); + } + last = Point::new(p.x, p.y); + } + PathEl::CurveTo(c1, c2, p) => { + if let Some(subpath) = current.as_mut() { + if let Some(knot) = subpath.knots.last_mut() { + knot.out_ctrl = Point::new(c1.x, c1.y); + } + subpath.knots.push(Knot { anchor: Point::new(p.x, p.y), in_ctrl: Point::new(c2.x, c2.y), out_ctrl: Point::new(p.x, p.y), smooth: false }); + } + last = Point::new(p.x, p.y); + } + PathEl::ClosePath => { + if let Some(mut subpath) = current.take() { + let restart = subpath.knots.first().map(|knot| knot.anchor); + subpath.closed = true; + if subpath.knots.len() > 1 { + let first = subpath.knots[0].anchor; + let last_anchor = subpath.knots.last().map_or(first, |knot| knot.anchor); + if (first.x - last_anchor.x).abs() < 1e-9 && (first.y - last_anchor.y).abs() < 1e-9 { + // A straight closing segment can merge into the first knot; a curve + // that returns to its start must keep both knots to preserve the loop. + let straight = subpath.knots.last().is_some_and(|knot| { + knot.in_ctrl.x == knot.anchor.x + && knot.in_ctrl.y == knot.anchor.y + && knot.out_ctrl.x == knot.anchor.x + && knot.out_ctrl.y == knot.anchor.y + }); + if straight && let Some(knot) = subpath.knots.pop() { + subpath.knots[0].in_ctrl = knot.in_ctrl; + } + } else { + subpath.knots[0].in_ctrl = first; + } + } + // A single-point closed subpath still paints a dot with a round cap. + if !restarted || subpath.knots.len() > 1 { + subpaths.push(subpath); + } + // A close starts a new subpath at the closed subpath's start point; a + // following line/curve continues from there (PDF 32000-1 §8.5.2.1). + if let Some(start) = restart { + current = Some(Subpath { closed: false, knots: vec![Knot::corner(start.x, start.y)], op: PathOp::Combine }); + last = start; + restarted = true; + } else { + restarted = false; + } + } + } + } + } + if let Some(subpath) = current + && (!restarted || subpath.knots.len() > 1) + { + subpaths.push(subpath); + } + *knots = knots.saturating_add(subpaths.iter().map(|subpath| subpath.knots.len()).sum::()); + if *knots > MAX_KNOTS { + return None; + } + for subpath in &mut subpaths { + for knot in &mut subpath.knots { + *knot = knot.transform(transform); + } + } + Some(Path::new(subpaths)) +} + +#[cfg(test)] +mod tests { + use lopdf::{Document as PdfDocument, Object, Stream, dictionary}; + + use super::*; + use crate::{ImportOptions, IoError, import_with_options_and_interrupt}; + + /// The embedded test font. + const INTER: &[u8] = include_bytes!("../../../assets/fonts/Inter-Regular.ttf"); + + /// A one-page 200 x 100 pt PDF whose content stream is `content`. + fn pdf(content: &str) -> Vec { + pdf_with_resources(content, dictionary! {}) + } + + /// [`pdf`] with page resources (for example an ExtGState). + fn pdf_with_resources(content: &str, resources: lopdf::Dictionary) -> Vec { + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec())); + let page_id = pdf.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(200.0), Object::Real(100.0)]), + "Contents" => content_id, + "Resources" => resources, + }); + pdf.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(vec![Object::Reference(page_id)]), + "Count" => 1, + }), + ); + let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id }); + pdf.trailer.set("Root", catalog); + let mut bytes = Vec::new(); + pdf.save_to(&mut bytes).expect("writing the fixture"); + bytes + } + + /// A one-page 200 x 100 pt PDF whose content stream is `content` and whose page uses an + /// embedded TrueType font as `/F1`. + fn text_pdf(content: &str) -> Vec { + text_pdf_named(content, "Inter-Regular") + } + + /// [`text_pdf`] with the font named `name` (the same Inter bytes, so tests can exercise the + /// name-based style rules). + fn text_pdf_named(content: &str, name: &str) -> Vec { + text_pdf_bytes(content, name, INTER) + } + + /// [`text_pdf`] with the font named `name` and the given font bytes. + fn text_pdf_bytes(content: &str, name: &str, font_bytes: &[u8]) -> Vec { + let mut pdf = PdfDocument::with_version("1.5"); + let pages_id = pdf.new_object_id(); + let font_file = pdf.add_object(Stream::new(dictionary! { "Length1" => font_bytes.len() as i64 }, font_bytes.to_vec())); + let descriptor = pdf.add_object(dictionary! { + "Type" => "FontDescriptor", + "FontName" => Object::Name(name.as_bytes().to_vec()), + "Flags" => 32, + "FontBBox" => Object::Array(vec![Object::Integer(-100), Object::Integer(-200), Object::Integer(1000), Object::Integer(900)]), + "ItalicAngle" => 0, + "Ascent" => 900, + "Descent" => -200, + "CapHeight" => 700, + "StemV" => 80, + "FontFile2" => font_file, + }); + let font = pdf.add_object(dictionary! { + "Type" => "Font", + "Subtype" => "TrueType", + "BaseFont" => Object::Name(name.as_bytes().to_vec()), + "FirstChar" => 32, + "LastChar" => 126, + "Widths" => Object::Array((32..=126u8).map(|c| { + let Ok(face) = ttf_parser::Face::parse(font_bytes, 0) else { return Object::Integer(600); }; + let width = face.glyph_index(char::from(c)).and_then(|id| face.glyph_hor_advance(id)).unwrap_or(0); + Object::Real(f32::from(width) * 1000.0 / f32::from(face.units_per_em())) + }).collect()), + "FontDescriptor" => descriptor, + "Encoding" => "WinAnsiEncoding", + }); + let content_id = pdf.add_object(Stream::new(dictionary! {}, content.as_bytes().to_vec())); + let page_id = pdf.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages_id, + "MediaBox" => Object::Array(vec![Object::Real(0.0), Object::Real(0.0), Object::Real(200.0), Object::Real(100.0)]), + "Contents" => content_id, + "Resources" => dictionary! { "Font" => dictionary! { "F1" => font } }, + }); + pdf.objects.insert( + pages_id, + Object::Dictionary(dictionary! { + "Type" => "Pages", + "Kids" => Object::Array(vec![Object::Reference(page_id)]), + "Count" => 1, + }), + ); + let catalog = pdf.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id }); + pdf.trailer.set("Root", catalog); + let mut bytes = Vec::new(); + pdf.save_to(&mut bytes).expect("writing the text fixture"); + bytes + } + + /// The artboard group's children. + fn children(document: &photocraft_doc::Document) -> &[Layer] { + match &document.layers.first().expect("a page group").content { + LayerContent::Group(group) => &group.children, + _ => panic!("the page is not a group"), + } + } + + /// The first text layer of `document`. + fn text_layer(document: &photocraft_doc::Document) -> &TextLayer { + children(document) + .iter() + .find_map(|layer| match &layer.content { + LayerContent::Text(text) => Some(text), + _ => None, + }) + .expect("a text layer") + } + + /// A solid fill or stroke colour. + fn solid(fill: &Fill) -> Color { + match fill { + Fill::Solid(color) => *color, + _ => panic!("not a solid paint"), + } + } + + /// Path bounds in document pixels. + fn bounds(path: &Path) -> (f64, f64, f64, f64) { + let mut b = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for knot in path.subpaths.iter().flat_map(|subpath| &subpath.knots) { + b.0 = b.0.min(knot.anchor.x); + b.1 = b.1.min(knot.anchor.y); + b.2 = b.2.max(knot.anchor.x); + b.3 = b.3.max(knot.anchor.y); + } + b + } + + #[test] + fn painted_paths_become_shape_layers_with_their_colours_and_dashes() { + let bytes = pdf("1 0 0 rg 20 20 60 40 re f 0 0 1 RG 3 w [9 4] 0 d 100 30 m 180 30 l S"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("paths.pdf", &bytes, &options, &Interrupt::NONE).expect("an editable import"); + let children = children(&imported.document); + assert_eq!(children.len(), 2, "one fill and one stroke layer"); + let LayerContent::Shape(fill) = &children[0].content else { panic!("the first child is not a shape") }; + assert_eq!(solid(fill.fill.as_ref().expect("a fill")), Color::rgb(1.0, 0.0, 0.0)); + assert!(fill.stroke.is_none()); + let (x0, y0, x1, y1) = bounds(&fill.path); + assert!((x0 - 20.0).abs() < 0.01 && (x1 - 80.0).abs() < 0.01, "x bounds {x0}..{x1}"); + assert!((y0 - 40.0).abs() < 0.01 && (y1 - 80.0).abs() < 0.01, "PDF y up becomes document y down: {y0}..{y1}"); + + let LayerContent::Shape(stroke) = &children[1].content else { panic!("the second child is not a shape") }; + assert!(stroke.fill.is_none()); + let stroke = stroke.stroke.as_ref().expect("a stroke"); + assert_eq!(solid(&stroke.paint), Color::rgb(0.0, 0.0, 1.0)); + assert!((stroke.width - 3.0).abs() < 0.01, "stroke width {}", stroke.width); + assert_eq!(stroke.dashes.len(), 2); + assert!((stroke.dashes[0] - 3.0).abs() < 0.01 && (stroke.dashes[1] - 4.0 / 3.0).abs() < 0.01, "dashes {:?}", stroke.dashes); + } + + #[test] + fn the_editable_composite_matches_the_raster_page() { + let bytes = pdf("1 0 0 rg 20 20 60 40 re f 0 0 1 RG 3 w [9 4] 0 d 100 30 m 180 30 l S"); + let raster = import_with_options_and_interrupt("paths.pdf", &bytes, &ImportOptions { pdf_dpi: 72.0, ..ImportOptions::default() }, &Interrupt::NONE) + .expect("a raster import"); + let editable = import_with_options_and_interrupt( + "paths.pdf", + &bytes, + &ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }, + &Interrupt::NONE, + ) + .expect("an editable import"); + let fmt = editable.document.pixel_format(); + let a = photocraft_compose::flatten_to_surface(&editable.document, fmt, None); + let b = photocraft_compose::flatten_to_surface(&raster.document, fmt, None); + let rect = editable.document.bounds(); + let av = a.read_region(rect); + let bv = b.read_region(rect); + assert_eq!(av.len(), bv.len()); + let mut sum = 0.0f64; + let mut max = 0.0f32; + for (x, y) in av.iter().zip(&bv) { + let d = (x - y).abs(); + sum += f64::from(d); + max = max.max(d); + } + let mean = sum / av.len() as f64; + assert!(mean < 0.01, "mean pixel difference {mean:.4} (max {max:.3})"); + } + + #[test] + fn text_falls_back_to_the_raster_page_with_a_warning() { + let bytes = pdf("BT /F1 24 Tf 10 50 Td (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("text.pdf", &bytes, &options, &Interrupt::NONE).expect("a fallback import"); + assert!( + imported.warnings.iter().any(|warning| warning.contains("text without an embedded font") && warning.contains("rasterised")), + "{:?}", + imported.warnings + ); + assert!(matches!(children(&imported.document).first().map(|layer| &layer.content), Some(LayerContent::Raster(_)))); + } + + #[test] + fn embedded_text_becomes_a_text_layer_with_its_style() { + let bytes = text_pdf("BT /F1 24 Tf 1 0 0 rg 20 50 Td (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("text.pdf", &bytes, &options, &Interrupt::NONE).expect("an editable text import"); + let text = text_layer(&imported.document); + assert_eq!(text.text, "Hi"); + assert!(text.font_family.starts_with("Inter"), "family {}", text.font_family); + assert!((f64::from(text.size_pt) - 24.0).abs() < 0.1, "size {}", text.size_pt); + assert_eq!(text.color, Color::rgb(1.0, 0.0, 0.0)); + let origin = text.transform.apply(Point::new(0.0, 0.0)); + assert!((origin.x - 20.0).abs() < 0.5 && (origin.y - 50.0).abs() < 0.5, "origin {origin:?}"); + assert!(text.cache.is_some(), "the text cache is rendered on import"); + let style = &text.runs[0].style; + assert_eq!(style.postscript_name.as_deref(), Some("Inter-Regular")); + assert_eq!(style.weight, 400); + assert!(!style.italic); + assert!(imported.warnings.iter().any(|warning| warning.contains("fonts embedded in the PDF")), "{:?}", imported.warnings); + } + + #[test] + fn imported_text_relayouts_with_the_shared_engine() { + let bytes = text_pdf("BT /F1 24 Tf 1 0 0 rg 20 50 Td (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("text.pdf", &bytes, &options, &Interrupt::NONE).expect("an editable text import"); + let mut text = text_layer(&imported.document).clone(); + text.cache = None; + let shared = photocraft_text::shared(); + let mut engine = shared.lock().unwrap_or_else(|error| error.into_inner()); + assert!(engine.has_family(&text.font_family), "the app engine must know the imported family"); + let rect = engine.render_layer(&mut text, 72.0, PixelFormat::new(ColorMode::Rgb, SampleType::U8, true)); + assert!(rect.width() > 0 && rect.height() > 0, "the layer re-lays out"); + assert!(text.cache.is_some()); + } + + #[test] + fn rotated_text_stays_editable() { + let bytes = text_pdf("BT /F1 24 Tf 0 1 -1 0 100 20 Tm (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("rotated.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + assert!(!imported.warnings.iter().any(|warning| warning.contains("skewed or mirrored")), "{:?}", imported.warnings); + assert_eq!(text_layer(&imported.document).text, "Hi"); + } + + #[test] + fn font_aliases_include_the_content_key() { + assert_ne!(font_alias("Inter-Regular", 1), font_alias("Inter-Regular", 2)); + assert!(font_alias("Inter-Regular", 0x12ab).contains("Inter-Regular")); + } + + #[test] + fn two_documents_with_one_font_name_keep_distinct_aliases() { + // Rename the bundled Inter family to one that is not installed, so the embedded face + // takes the alias path; same PostScript name and family, different bytes (a trailing byte + // changes the content key), as two different subsets of one font would. + let mut base = INTER.to_vec(); + for at in 0..base.len().saturating_sub(5) { + if &base[at..at + 5] == b"Inter" { + base[at..at + 5].copy_from_slice(b"Xntr"); + } + } + let mut other = base.clone(); + other.push(0); + let a = text_pdf_bytes("BT /F1 24 Tf 20 50 Td (Hi) Tj ET", "Xntr-Regular", &base); + let b = text_pdf_bytes("BT /F1 24 Tf 20 50 Td (Hi) Tj ET", "Xntr-Regular", &other); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let first = import_with_options_and_interrupt("a.pdf", &a, &options, &Interrupt::NONE).expect("first import"); + let second = import_with_options_and_interrupt("b.pdf", &b, &options, &Interrupt::NONE).expect("second import"); + let fa = text_layer(&first.document).font_family.clone(); + let fb = text_layer(&second.document).font_family.clone(); + assert_ne!(fa, fb, "the two embedded faces must not share an alias"); + let shared = photocraft_text::shared(); + let mut engine = shared.lock().unwrap_or_else(|error| error.into_inner()); + assert!(engine.has_family(&fa) && engine.has_family(&fb)); + } + + #[test] + fn mirrored_text_falls_back() { + let bytes = text_pdf("BT /F1 24 Tf -1 0 0 1 100 50 Tm (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("mirror.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + assert!( + imported.warnings.iter().any(|warning| warning.contains("skewed or mirrored text") && warning.contains("rasterised")), + "{:?}", + imported.warnings + ); + } + + #[test] + fn font_names_set_bold_and_italic() { + for (name, weight, italic) in [("Inter-Bold", 700, false), ("Inter-Italic", 400, true), ("Inter-BoldItalic", 700, true)] { + let bytes = text_pdf_named("BT /F1 24 Tf 20 50 Td (Hi) Tj ET", name); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("text.pdf", &bytes, &options, &Interrupt::NONE).expect("an editable text import"); + let style = &text_layer(&imported.document).runs[0].style; + assert_eq!(style.weight, weight, "{name}"); + assert_eq!(style.italic, italic, "{name}"); + assert!(style.font_family.starts_with("Inter"), "{name}: {}", style.font_family); + } + } + + #[test] + fn a_page_sized_clip_does_not_force_a_raster_page() { + let bytes = pdf("q 0 0 200 100 re W n 1 0 0 rg 20 20 60 40 re f Q"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("clip.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + assert!(!imported.warnings.iter().any(|warning| warning.contains("clipping")), "{:?}", imported.warnings); + assert!(children(&imported.document).iter().any(|layer| matches!(layer.content, LayerContent::Shape(_)))); + } + + #[test] + fn a_zero_width_stroke_is_a_one_pixel_hairline() { + let bytes = pdf("0 0 1 RG 0 w 20 30 m 180 30 l S"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("hairline.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + let LayerContent::Shape(shape) = &children(&imported.document)[0].content else { panic!("not a shape") }; + let stroke = shape.stroke.as_ref().expect("a stroke"); + assert!((stroke.width - 1.0).abs() < 0.01, "width {}", stroke.width); + } + + #[test] + fn a_non_uniform_stroke_transform_falls_back() { + let bytes = pdf("q 2 0 0 1 0 0 cm 0 0 1 RG 4 w 20 30 m 80 30 l S Q"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("skew.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + assert!( + imported.warnings.iter().any(|warning| warning.contains("non-uniform stroke transform") && warning.contains("rasterised")), + "{:?}", + imported.warnings + ); + assert!(matches!(children(&imported.document).first().map(|layer| &layer.content), Some(LayerContent::Raster(_)))); + } + + #[test] + fn a_uniform_stroke_transform_scales_the_width() { + let bytes = pdf("q 2 0 0 2 0 0 cm 0 0 1 RG 4 w 20 30 m 80 30 l S Q"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("scaled.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + let LayerContent::Shape(shape) = &children(&imported.document)[0].content else { panic!("not a shape") }; + let stroke = shape.stroke.as_ref().expect("a stroke"); + assert!((stroke.width - 8.0).abs() < 0.01, "width {}", stroke.width); + } + + #[test] + fn extgstate_fill_and_stroke_opacity_reach_the_layers() { + let resources = dictionary! { + "ExtGState" => dictionary! { + "GS0" => dictionary! { "ca" => 0.5, "CA" => 0.5 }, + }, + }; + let bytes = pdf_with_resources("/GS0 gs 0.2 0.4 0.6 rg 20 20 60 40 re f 0 0 1 RG 4 w 20 80 m 180 80 l S", resources); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("opacity.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + let layers = children(&imported.document); + let LayerContent::Shape(fill) = &layers[0].content else { panic!("not a shape") }; + let fill = solid(fill.fill.as_ref().expect("a fill")); + assert!((fill.alpha - 0.5).abs() < 0.01); + assert!((fill.c[0] - 0.2).abs() < 0.01 && (fill.c[1] - 0.4).abs() < 0.01 && (fill.c[2] - 0.6).abs() < 0.01, "{fill:?}"); + let LayerContent::Shape(stroke) = &layers[1].content else { panic!("not a shape") }; + assert!((solid(&stroke.stroke.as_ref().expect("a stroke").paint).alpha - 0.5).abs() < 0.01); + } + + #[test] + fn odd_and_zero_dash_arrays_are_normalised() { + let mut stroke = craft_pdf::interpret::StrokeProps { + line_width: 2.0, + line_cap: Cap::Butt, + line_join: Join::Miter, + miter_limit: 10.0, + dash_array: Default::default(), + dash_offset: 0.0, + }; + stroke.dash_array.push(3.0); + let out = to_stroke(&stroke, Color::BLACK, 1.0).expect("a stroke"); + assert_eq!(out.dashes, vec![1.5, 1.5], "an odd array repeats"); + stroke.dash_array.clear(); + stroke.dash_array.push(0.0); + stroke.dash_array.push(4.0); + let out = to_stroke(&stroke, Color::BLACK, 1.0).expect("a stroke"); + assert_eq!(out.dashes, vec![0.0, 2.0], "zero-length dashes stay"); + } + + #[test] + fn fill_then_stroke_text_is_fake_bold_not_a_second_run() { + let bytes = text_pdf("BT /F1 24 Tf 2 Tr 1 0 0 rg 1 0 0 RG 20 50 Td (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("text.pdf", &bytes, &options, &Interrupt::NONE).expect("an editable text import"); + let texts: Vec<_> = children(&imported.document) + .iter() + .filter_map(|layer| match &layer.content { + LayerContent::Text(text) => Some(text), + _ => None, + }) + .collect(); + assert_eq!(texts.len(), 1, "one run, not a duplicate stroke run"); + assert_eq!(texts[0].text, "Hi"); + assert_eq!(texts[0].runs[0].style.weight, 700); + assert_eq!(texts[0].color, Color::rgb(1.0, 0.0, 0.0)); + } + + #[test] + fn font_family_rules_follow_the_base_font() { + assert_eq!(family_from_postscript("ABCDEF+TimesNewRomanPSMT"), "Times New Roman"); + assert_eq!(family_from_postscript("Arial-BoldMT"), "Arial"); + assert_eq!(family_from_postscript("Helvetica-Oblique"), "Helvetica"); + assert_eq!(family_from_postscript("MS-Gothic"), "MS-Gothic"); + assert_eq!(family_from_postscript("SimSun"), "Sim Sun"); + assert_eq!(family_from_postscript("Inter-Regular"), "Inter"); + assert_eq!(family_from_postscript("Roboto-Black"), "Roboto"); + } + + #[test] + fn the_editable_text_composite_matches_the_raster_page() { + let bytes = text_pdf("BT /F1 24 Tf 1 0 0 rg 20 50 Td (Hi) Tj ET"); + let raster = import_with_options_and_interrupt("text.pdf", &bytes, &ImportOptions { pdf_dpi: 72.0, ..ImportOptions::default() }, &Interrupt::NONE) + .expect("a raster import"); + let editable = import_with_options_and_interrupt( + "text.pdf", + &bytes, + &ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }, + &Interrupt::NONE, + ) + .expect("an editable import"); + let fmt = editable.document.pixel_format(); + let a = photocraft_compose::flatten_to_surface(&editable.document, fmt, None); + let b = photocraft_compose::flatten_to_surface(&raster.document, fmt, None); + let rect = editable.document.bounds(); + let av = a.read_region(rect); + let bv = b.read_region(rect); + let mut sum = 0.0f64; + let mut max = 0.0f32; + for (x, y) in av.iter().zip(&bv) { + let d = (x - y).abs(); + sum += f64::from(d); + max = max.max(d); + } + let mean = sum / av.len() as f64; + assert!(mean < 0.02, "mean pixel difference {mean:.4} (max {max:.3})"); + // The cache must actually contain text: a blank layer can still pass a mean comparison. + let channels = fmt.channels(); + let width = rect.width() as usize; + let mut red = 0; + for y in 30..60usize { + for x in 20..45usize { + let at = (y * width + x) * channels; + if av[at] > 0.4 && av[at + 1] < 0.4 && av[at + 2] < 0.4 { + red += 1; + } + } + } + assert!(red > 0, "the editable text cache is blank"); + } + + #[test] + fn text_keeps_paint_order_on_both_sides_of_a_path() { + let bytes = text_pdf("BT /F1 24 Tf 20 50 Td (A) Tj ET 0 0 1 rg 0 0 200 100 re f BT /F1 24 Tf 20 20 Td (B) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("order.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + let layers = children(&imported.document); + assert_eq!(layers.len(), 3); + let text = |layer: &Layer| match &layer.content { + LayerContent::Text(text) => text.text.clone(), + _ => String::new(), + }; + assert_eq!(text(&layers[0]), "A"); + assert!(matches!(layers[1].content, LayerContent::Shape(_)), "the path stays between the runs"); + assert_eq!(text(&layers[2]), "B"); + } + + #[test] + fn fake_bold_does_not_pair_across_a_path() { + let bytes = text_pdf("BT /F1 24 Tf 20 50 Td (Hi) Tj ET 0 0 1 rg 0 0 200 100 re f BT /F1 24 Tf 1 Tr 1 w 0 0 1 RG 20 50 Td (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("pair.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + assert!(imported.warnings.iter().any(|warning| warning.contains("stroked text") && warning.contains("rasterised")), "{:?}", imported.warnings); + } + + #[test] + fn a_curve_returning_to_its_start_keeps_both_knots() { + let mut bez = BezPath::new(); + bez.move_to((0.0, 0.0)); + bez.curve_to((10.0, 0.0), (10.0, 10.0), (0.0, 0.0)); + bez.close_path(); + let mut knots = 0; + let path = to_path(&bez, &Affine::IDENTITY, &mut knots).expect("a path"); + assert_eq!(path.subpaths.len(), 1); + assert!(path.subpaths[0].knots.len() >= 2); + } + + #[test] + fn an_explicitly_closed_rectangle_is_a_no_op_clip() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((200.0, 0.0)); + path.line_to((200.0, 100.0)); + path.line_to((0.0, 100.0)); + path.line_to((0.0, 0.0)); + path.close_path(); + assert_eq!(axis_aligned_rect(&path), Some((0.0, 0.0, 200.0, 100.0))); + } + + #[test] + fn a_dashed_zero_length_line_falls_back() { + let bytes = pdf("[1 1] 0 d 10 10 m 20 20 l 30 30 m h S"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("dash.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + assert!( + imported.warnings.iter().any(|warning| warning.contains("dashed zero-length subpath") && warning.contains("rasterised")), + "{:?}", + imported.warnings + ); + } + + #[test] + fn a_solid_zero_length_line_stays_editable() { + let bytes = pdf("10 10 m 20 20 l 30 30 m h S"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("solid.pdf", &bytes, &options, &Interrupt::NONE).expect("import"); + let layers = children(&imported.document); + assert!(layers.iter().any(|layer| matches!(layer.content, LayerContent::Shape(_))), "{:?}", imported.warnings); + } + + #[test] + fn a_closed_single_point_subpath_is_retained() { + let mut bez = BezPath::new(); + bez.move_to((10.0, 10.0)); + bez.close_path(); + let mut knots = 0; + let path = to_path(&bez, &Affine::IDENTITY, &mut knots).expect("a path"); + assert_eq!(path.subpaths.len(), 1); + assert_eq!(path.subpaths[0].knots.len(), 1); + assert!(path.subpaths[0].closed); + } + + #[test] + fn a_bow_tie_path_is_not_a_no_op_clip() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((10.0, 10.0)); + path.line_to((10.0, 0.0)); + path.line_to((0.0, 10.0)); + path.close_path(); + assert!(axis_aligned_rect(&path).is_none()); + } + + #[test] + fn a_line_after_close_starts_a_new_subpath() { + let mut bez = BezPath::new(); + bez.move_to((0.0, 0.0)); + bez.line_to((10.0, 0.0)); + bez.line_to((10.0, 10.0)); + bez.close_path(); + bez.line_to((20.0, 0.0)); + let mut knots = 0; + let path = to_path(&bez, &Affine::IDENTITY, &mut knots).expect("a path"); + assert_eq!(path.subpaths.len(), 2); + assert_eq!(path.subpaths[1].knots[0].anchor, Point::new(0.0, 0.0)); + assert_eq!(path.subpaths[1].knots.last().expect("a knot").anchor, Point::new(20.0, 0.0)); + } + + #[test] + fn cancelling_between_objects_stops_the_editable_page() { + let mut content = String::from("1 0 0 rg\n"); + for i in 0..20 { + content.push_str(&format!("{} 20 20 20 re f\n", i * 8)); + } + let bytes = pdf(&content); + let calls = std::sync::atomic::AtomicUsize::new(0); + let cancel = || calls.fetch_add(1, Ordering::SeqCst) >= 3; + let ctl = Interrupt::cancel_only(&cancel); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + assert!(matches!(import_with_options_and_interrupt("objects.pdf", &bytes, &options, &ctl), Err(IoError::Cancelled))); + } + + #[test] + fn a_cancelled_editable_import_returns_cancelled() { + let bytes = pdf("1 0 0 rg 20 20 60 40 re f"); + let cancel = || true; + let ctl = Interrupt::cancel_only(&cancel); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + assert!(matches!(import_with_options_and_interrupt("paths.pdf", &bytes, &options, &ctl), Err(IoError::Cancelled))); + } + #[test] + fn positioned_pdf_text_is_not_silently_reflowed() { + let bytes = text_pdf("BT /F1 24 Tf 20 50 Td [(H) -900 (i)] TJ ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("spacing.pdf", &bytes, &options, &Interrupt::NONE).unwrap(); + assert!(children(&imported.document).iter().all(|l| matches!(l.content, LayerContent::Raster(_))), "unrepresentable spacing must rasterise"); + assert!(imported.warnings.iter().any(|w| w.contains("rasterised"))); + } + + #[test] + fn colored_text_outlines_are_not_fake_bold() { + let bytes = text_pdf("BT /F1 24 Tf 1 0 0 rg 0 0 1 RG 1 w 2 Tr 20 50 Td (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("outline.pdf", &bytes, &options, &Interrupt::NONE).unwrap(); + assert!(children(&imported.document).iter().all(|l| matches!(l.content, LayerContent::Raster(_))), "a blue outline cannot become red bold text"); + } + + #[test] + fn a_shape_cache_keeps_the_whole_miter() { + let bytes = pdf("10 w 10 M 40 20 m 50 70 l 60 20 l S"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("miter.pdf", &bytes, &options, &Interrupt::NONE).unwrap(); + let layer = children(&imported.document).first().unwrap(); + let LayerContent::Shape(shape) = &layer.content else { panic!("expected an editable stroke") }; + let board = Rect::from_xywh(0, 0, 200, 100); + let expected = photocraft_vector::render_shape(shape, imported.document.pixel_format(), board); + assert!(shape.cache.as_ref().unwrap().read_region(board) == expected.read_region(board), "bounds must include the pointed join"); + } + + #[test] + fn cache_budget_charges_full_tiles_and_preserves_the_limit() { + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); + let tile_bytes = TILE_SIZE as u64 * TILE_SIZE as u64 * fmt.bytes_per_pixel() as u64; + let mut used = MAX_CACHE_BYTES - tile_bytes; + admit_cache(&mut used, Rect::from_xywh(0, 0, 1, 1), fmt).unwrap(); + assert_eq!(used, MAX_CACHE_BYTES); + assert_eq!(admit_cache(&mut used, Rect::from_xywh(0, 0, 1, 1), fmt), Err(EditableError::Unsupported("page cache budget"))); + assert_eq!(used, MAX_CACHE_BYTES); + let mut used = 0; + admit_cache(&mut used, Rect::from_xywh(-1, -1, 2, 2), fmt).unwrap(); + assert_eq!(used, 4 * tile_bytes, "a tiny rectangle may straddle four tiles"); + } + + #[test] + fn text_cache_respects_the_budget_already_used_by_shapes() { + let bytes = text_pdf("BT /F1 24 Tf 20 50 Td (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("text-budget.pdf", &bytes, &options, &Interrupt::NONE).unwrap(); + let mut text = text_layer(&imported.document).clone(); + text.cache = None; + let mut layers = vec![Layer::new("Text", LayerContent::Text(text))]; + let mut cached = MAX_CACHE_BYTES; + assert_eq!( + render_text_caches(&mut layers, 72.0, imported.document.pixel_format(), &Interrupt::NONE, &mut cached), + Err(EditableError::Unsupported("page cache budget")) + ); + let LayerContent::Text(text) = &layers[0].content else { panic!("text layer") }; + assert!(text.cache.is_none(), "reject before allocating the text cache"); + } + + #[test] + fn multiple_text_caches_share_one_allowance() { + let bytes = text_pdf("BT /F1 24 Tf 20 50 Td (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("text-budget.pdf", &bytes, &options, &Interrupt::NONE).unwrap(); + let mut text = text_layer(&imported.document).clone(); + text.cache = None; + let fmt = imported.document.pixel_format(); + let layout = photocraft_text::shared().lock().unwrap().layout(&text, 72.0); + let area = photocraft_text::render::ink_rect(&layout, &text.transform); + let mut one_cache = 0; + admit_cache(&mut one_cache, area, fmt).unwrap(); + assert!(one_cache > 0); + let mut layers = vec![Layer::new("First", LayerContent::Text(text.clone())), Layer::new("Second", LayerContent::Text(text))]; + let mut cached = MAX_CACHE_BYTES - one_cache; + assert_eq!(render_text_caches(&mut layers, 72.0, fmt, &Interrupt::NONE, &mut cached), Err(EditableError::Unsupported("page cache budget"))); + assert_eq!(cached, MAX_CACHE_BYTES); + assert!(matches!(&layers[0].content, LayerContent::Text(t) if t.cache.is_some())); + assert!(matches!(&layers[1].content, LayerContent::Text(t) if t.cache.is_none())); + let mut cached = 0; + render_text_caches(&mut layers, 72.0, fmt, &Interrupt::NONE, &mut cached).unwrap(); + assert_eq!(cached, one_cache * 2); + assert!(layers.iter().all(|l| matches!(&l.content, LayerContent::Text(t) if t.cache.is_some()))); + } + #[test] + fn thick_text_outlines_are_not_fake_bold() { + let bytes = text_pdf("BT /F1 24 Tf 1 0 0 rg 1 0 0 RG 5 w 2 Tr 20 50 Td (Hi) Tj ET"); + let options = ImportOptions { pdf_dpi: 72.0, pdf_editable: true, ..ImportOptions::default() }; + let imported = import_with_options_and_interrupt("thick-outline.pdf", &bytes, &options, &Interrupt::NONE).unwrap(); + assert!(children(&imported.document).iter().all(|l| matches!(l.content, LayerContent::Raster(_)))); + } +} diff --git a/crates/io/src/pdf_import.rs b/crates/io/src/pdf_import.rs index d55676ac16..b55da30bec 100644 --- a/crates/io/src/pdf_import.rs +++ b/crates/io/src/pdf_import.rs @@ -135,6 +135,8 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let mut doc = Document::new(name, Size::new(doc_width as u32, doc_height as u32), ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = dpi as f32; + #[cfg(feature = "pdf-editable")] + let mut editable_text = false; let mut x: u32 = 0; for (index, &(width_pt, height_pt)) in sizes.iter().enumerate() { ctl.check().map_err(|_| IoError::Cancelled)?; @@ -147,6 +149,30 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - if width > raster::MAX_SIDE || height > raster::MAX_SIDE || u64::from(width) * u64::from(height) > raster::MAX_PIXELS { return Err(IoError::Unsupported(format!("PDF page {page_number} is too large at {dpi:.0} dpi; lower the import DPI"))); } + let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); + #[cfg(feature = "pdf-editable")] + if opts.pdf_editable { + match crate::pdf_editable::page(page, rect, ctl) { + Ok(layers) => { + if layers.iter().any(|layer| matches!(&layer.content, LayerContent::Text(_))) { + editable_text = true; + } + let group = Group { children: layers, expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; + doc.layers.push(Layer::new(format!("Page {page_number}"), LayerContent::Group(group))); + x = x.saturating_add(width).saturating_add(GAP); + ctl.progress((index + 1) as f32 / count as f32); + continue; + } + Err(crate::pdf_editable::EditableError::Cancelled) => return Err(IoError::Cancelled), + Err(crate::pdf_editable::EditableError::Unsupported(reason)) => { + warnings.push(format!("PDF page {page_number}: {reason}; the page was rasterised")); + } + } + } + #[cfg(not(feature = "pdf-editable"))] + if opts.pdf_editable { + warnings.push(format!("PDF page {page_number}: editable PDF import is not built into this binary; the page was rasterised")); + } // A cache per page, deliberately: a shared one would keep decoded images and fonts alive // across up to 16 pages outside the pixel budget, and would hide an image-decode warning // on a later page after the page that first hit it. @@ -195,13 +221,16 @@ pub fn import(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &Interrupt) - let band_height = (rows.len() / row_bytes) as u32; surface.write_region(Rect::from_xywh(x as i32, top, width, band_height), &data); } - let rect = Rect::new(x as i32, 0, (x + width) as i32, height as i32); let layer = Layer::new(format!("Page {page_number}"), LayerContent::Raster(surface)); let group = Group { children: vec![layer], expanded: true, artboard: Some(Artboard::new(rect)), frame_stroke: None }; doc.layers.push(Layer::new(format!("Page {page_number}"), LayerContent::Group(group))); x = x.saturating_add(width).saturating_add(GAP); ctl.progress((index + 1) as f32 / count as f32); } + #[cfg(feature = "pdf-editable")] + if editable_text { + warnings.push("PDF text uses fonts embedded in the PDF; it may change font when edited or reopened".into()); + } Ok(ImportResult { warnings, document: doc, source_read_only: false, preview_only: false }) } diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rs index a1ed4aaa01..23d9d5a5ea 100644 --- a/crates/io/src/raw.rs +++ b/crates/io/src/raw.rs @@ -50,7 +50,7 @@ fn upright_preview(raw: &[u8], jpeg: &[u8], limits: &photocraft_raw::Limits) -> /// Camera Raw's Temperature, Tint, Exposure, Shadows, Highlights, Clarity, Texture and Dehaze, /// applied while developing the sensor data (the open-time Camera Raw dialog) instead of to the -/// developed RGB pixels, and the demosaic method. +/// developed RGB pixels, the demosaic method, and the crop. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct RawTuning { /// −100…100, as `photocraft_algo::camera_raw::CameraRaw::temperature`. @@ -71,6 +71,9 @@ pub struct RawTuning { pub texture: f32, /// −100…100, as `CameraRaw::dehaze`. pub dehaze: f32, + /// The crop of the raw's sidecar ([`crate::camera_raw_xmp::Crop`], in the stored + /// orientation): the developed frame is cropped to it once it is upright. + pub crop: Option, } /// Develops a raw file with `tuning` applied at the raw stage: Exposure as develop exposure, @@ -106,7 +109,15 @@ pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result< } None => false, }; - let dev = photocraft_raw::develop_sensor(&sensor, &opts).map_err(IoError::Raw)?; + let mut dev = photocraft_raw::develop_sensor(&sensor, &opts).map_err(IoError::Raw)?; + let cropped = match tuning.crop { + Some(crop) => { + let o = if opts.orient { dev.info.orientation } else { 1 }; + crop_developed(&mut dev, crop.oriented(o))?; + format!(", cropped to {}×{}", dev.width, dev.height) + } + None => String::new(), + }; let wb = if wb_applied { format!("as-shot white balance, temperature {:+.0}, tint {:+.0}", tuning.temperature, tuning.tint) } else { @@ -117,10 +128,26 @@ pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result< .filter(|(_, v)| *v != 0.0) .map(|(k, v)| format!(", {k} {v:+.0}")) .collect::(); - let summary = format!("developed in Camera Raw (exposure {:+.2} EV{tone}, {wb}, {} demosaic)", tuning.exposure, tuning.demosaic.id()); + let summary = format!("developed in RAW Develop (exposure {:+.2} EV{tone}, {wb}, {} demosaic{cropped})", tuning.exposure, tuning.demosaic.id()); Ok((developed_document(name, bytes, format, dev, &summary)?, wb_applied)) } +/// Crops the upright developed frame to `crop` (fractions of it), as Camera Raw crops a raw. +fn crop_developed(dev: &mut photocraft_raw::Developed, crop: crate::camera_raw_xmp::Crop) -> Result<(), IoError> { + let (w, h) = (dev.width as usize, dev.height as usize); + let bad = || IoError::Raw(RawError::Malformed(format!("the developed {w}x{h} frame holds fewer samples than its size"))); + let Some((x0, y0, x1, y1)) = crop.pixels(w, h) else { return Ok(()) }; + let mut rgb = Vec::with_capacity((x1 - x0) * (y1 - y0) * 3); + for y in y0..y1 { + let row = y.checked_mul(w).ok_or_else(bad)?; + rgb.extend_from_slice(dev.rgb.get((row + x0) * 3..(row + x1) * 3).ok_or_else(bad)?); + } + dev.rgb = rgb; + dev.width = u32::try_from(x1 - x0).map_err(|_| bad())?; + dev.height = u32::try_from(y1 - y0).map_err(|_| bad())?; + Ok(()) +} + /// The tone curve `bytes` develop with by default: the fitted look's for a file without colour /// calibration (see [`import_raw_with`]), else the camera profile's (empty: none, or not a raw /// this crate decodes). For previews of the open-time raw-stage sliders diff --git a/crates/io/tests/it/raw.rs b/crates/io/tests/it/raw.rs index 52250c24d7..12a3d362e4 100644 --- a/crates/io/tests/it/raw.rs +++ b/crates/io/tests/it/raw.rs @@ -420,6 +420,36 @@ fn uncalibrated_raw_takes_its_colour_from_the_camera_jpeg() { assert_eq!(r.document.depth, SampleType::U16); } +/// #9985: a sidecar's crop is measured on the raw as stored, before its Orientation turns it +/// upright: the developed frame is cropped to the same sensor pixels, whichever way it is turned. +#[test] +fn camera_raw_tuning_crops_in_the_stored_orientation() { + use photocraft_io::camera_raw_xmp::Crop; + use photocraft_io::raw::{RawTuning, import_raw_tuned}; + let (w, h) = (40, 24); + // Stored pixels x 4..24, y 6..18; then the upright frame's size and the same pixels in it. + let crop = Crop { top: 0.25, left: 0.1, bottom: 0.75, right: 0.6 }; + for (orientation, size, [x0, y0, x1, y1]) in + [(1, (40, 24), [4, 6, 24, 18]), (3, (40, 24), [16, 6, 36, 18]), (6, (24, 40), [6, 4, 18, 24]), (8, (24, 40), [6, 16, 18, 36])] + { + let mut spec = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 65535)); + spec.as_shot_neutral = Some([0.6, 1.0, 0.8]); + spec.orientation = orientation; + let bytes = spec.build(); + let (full, _) = import_raw_tuned("shot.dng", &bytes, &RawTuning::default()).unwrap(); + let (cut, _) = import_raw_tuned("shot.dng", &bytes, &RawTuning { crop: Some(crop), ..Default::default() }).unwrap(); + assert_eq!((full.document.size.width, full.document.size.height), size, "orientation {orientation}"); + assert_eq!((cut.document.size.width, cut.document.size.height), (x1 - x0, y1 - y0), "orientation {orientation}"); + assert!(cut.warnings.iter().any(|n| n.contains(&format!("cropped to {}×{}", x1 - x0, y1 - y0))), "{:?}", cut.warnings); + let full = photocraft_io::document_to_image(&full.document, &mut Vec::new()).unwrap(); + let cut = photocraft_io::document_to_image(&cut.document, &mut Vec::new()).unwrap(); + // 16-bit RGB: 6 bytes a pixel. + let row = |y: u32| &full.data()[((y * size.0 + x0) * 6) as usize..((y * size.0 + x1) * 6) as usize]; + let expected: Vec = (y0..y1).flat_map(|y| row(y).to_vec()).collect(); + assert_eq!(cut.data(), expected, "orientation {orientation}: the crop is the same pixels of the uncropped develop"); + } +} + #[test] fn camera_raw_tuning_keeps_the_default_look_and_applies_user_gains_after_fitting() { use photocraft_io::raw::{RawTuning, fit_preview_look, import_raw_tuned}; diff --git a/crates/paint/src/bg_erase.rs b/crates/paint/src/bg_erase.rs index 323a90036a..facf783e83 100644 --- a/crates/paint/src/bg_erase.rs +++ b/crates/paint/src/bg_erase.rs @@ -4,6 +4,7 @@ //! Colours are compared in the surface's own colour channels (RGB, CMYK, Gray, Lab… at any depth), //! so nothing is converted through RGB; only alpha changes. +use photocraft_color::{SampleType, read_sample, write_sample}; use photocraft_geom::Rect; use photocraft_raster::{Surface, from_rgba}; use serde::{Deserialize, Serialize}; @@ -16,10 +17,17 @@ use crate::retouch::{Footprint, Region, alpha_index, apply_dab_stroke}; #[serde(default, rename_all = "camelCase")] pub struct BgEraseSettings { pub sampling: Sampling, + /// Which matching pixels are erased. [`Limits::FindEdges`] grades the erase over the Tolerance + /// like [`Limits::Contiguous`] in this tool (#11904), unlike Color Replacement, where it turns + /// the soft falloff off. pub limits: Limits, - /// 0..1: largest per-channel difference from the sampled colour that is erased. + /// 0..1: how far from the sampled colour a colour is still partly erased. The distance is the + /// largest increase plus the largest decrease over the colour channels (`dist`); an exact + /// match is erased fully, then less the further a colour is, and colours at or beyond the + /// Tolerance are kept (`graded_weight`). pub tolerance: f32, - /// Keep pixels that match the foreground colour. + /// Keep the foreground colour: the erase narrows to the colours between the sampled colour and + /// the foreground colour (see [`protected_tolerance`]). pub protect_foreground: bool, /// Straight RGBA foreground colour (for Protect Foreground Color). pub foreground: [f32; 4], @@ -40,9 +48,52 @@ impl Default for BgEraseSettings { } } -/// Largest per-channel difference over the colour channels. +/// Colour distance of `a` from `b` over the colour channels: the largest increase plus the largest +/// decrease (#11901). Changes in the same direction count like the largest of them; changes in +/// opposite directions add up, as the reference application measures them (a red-to-green edge is +/// about twice as far as one channel alone). One channel (Gray) gives the absolute difference. fn dist(a: &[f32], b: &[f32]) -> f32 { - a.iter().zip(b).fold(0.0f32, |m, (x, y)| m.max((x - y).abs())) + let (up, down) = a.iter().zip(b).fold((0.0f32, 0.0f32), |(up, down), (x, y)| { + let diff = x - y; + (up.max(diff), down.max(-diff)) + }); + up + down +} + +/// The Tolerance Protect Foreground Color leaves (#11903): it narrows to `limit`, the distance from +/// the sampled colour to the foreground colour, so the sampled colour itself is still erased, the +/// erase fades out towards the foreground, and colours at least as far from the sample as the +/// foreground (the foreground itself included) are kept. `None` when the foreground is the sampled +/// colour: nothing is erased. +fn protected_tolerance(tol: f32, limit: f32) -> Option { + if limit.is_nan() || limit <= 0.0 { + return None; + } + Some(tol.min(limit)) +} + +/// `v` as the document stores it: rounded to the 8- or 16-bit levels, unchanged in 32-bit float. +/// The sampled colour is read from stored pixels, so the foreground is compared at the same +/// precision; otherwise a foreground between two levels misses its own stored colour (#11903). +fn at_sample_precision(sample: SampleType, v: f32) -> f32 { + let mut bytes = [0u8; 4]; + write_sample(&mut bytes, sample, 0, v); + read_sample(&bytes, sample, 0) +} + +/// The match weight of one dab for a colour `d` away from the sampled colour (#11901): an exact +/// match is erased fully, then the weight falls off linearly over the whole Tolerance `tol` after +/// a short plateau `d0 = min(tol / 20, 8 levels)`, and colours at or beyond the Tolerance are kept. +/// Measured in the reference application with single clicks (one dab) at Tolerance 10 to 100. +fn graded_weight(d: f32, tol: f32) -> f32 { + if !d.is_finite() || d >= tol { + return if d <= 0.0 { 1.0 } else { 0.0 }; + } + let d0 = (tol / 20.0).min(8.0 / 255.0); + if d <= d0 { + return 1.0; + } + (1.0 - (d - d0) / (tol - d0)).clamp(0.0, 1.0) } /// Erase along `stroke`. The brush opacity is ignored (Photoshop's Background Eraser has none); @@ -70,22 +121,12 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option Vec { from_rgba(&fmt, [c[0], c[1], c[2], 1.0])[..nc].to_vec() }; let swatch = native(bs.background); - let fg = native(bs.foreground); + let fg: Vec = native(bs.foreground).into_iter().map(|v| at_sample_precision(fmt.sample, v)).collect(); let (sampling, limits, protect_foreground) = (bs.sampling, bs.limits, bs.protect_foreground); + let float = fmt.sample == SampleType::F32; let mut once: Option>> = None; - let match_w = move |d: f32| -> f32 { - if d > tol { - 0.0 - } else if soft && tol > 0.0 { - // Soft falloff over the last quarter of the tolerance. - ((tol - d) / (tol * 0.25)).clamp(0.0, 1.0) - } else { - 1.0 - } - }; let pre = pre.clone(); // The pixels before the stroke under the working copy, read once per working area. Sampling // and matching read these, so a dab landing on pixels earlier dabs already erased still @@ -116,28 +157,50 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option Some(swatch.clone()), }; let Some(sampled) = sampled else { return }; + // Protect Foreground Color narrows the Tolerance to the foreground colour (#11903), by the + // same distance as the sample match: the reference application measures a foreground that + // is off in two channels that way too. + let tol = if protect_foreground { + let Some(t) = protected_tolerance(tol, dist(&sampled, &fg)) else { return }; + t + } else { + tol + }; + // Find Edges grades soft edges like Contiguous does instead of cutting them hard (#11904): + // the reference application keeps at least as much of a blurred transition with it. + let match_w = |d: f32| -> f32 { graded_weight(d, tol) }; let (w, h) = (r.width() as usize, r.height() as usize); - // Per-pixel match weight from the pre-stroke colours: the contiguous fill passes through - // pixels this stroke already erased. + // Which pixels the contiguous fill may pass, from the pre-stroke colours as before: it + // passes through pixels this stroke already erased. + let mut reach = vec![0.0f32; w * h]; + // Per-pixel match weight from the working copy (#11902): a pixel an earlier dab erased + // partly is matched by its current, decontaminated colour, which is pushed away from the + // sampled colour, so later dabs erase it again only while it is still within the Tolerance. let mut weight = vec![0.0f32; w * h]; for y in r.y0..r.y1 { for x in r.x0..r.x1 { if fp.at(x, y) <= 0.0 { continue; } - let p = orig.px(x, y); - if p[a] <= 0.0 { + let o = orig.px(x, y); + if o[a] <= 0.0 { continue; } - let c = &p[..nc]; - if protect_foreground && dist(c, &fg) <= tol { - continue; + let i = (y - r.y0) as usize * w + (x - r.x0) as usize; + reach[i] = match_w(dist(&o[..nc], &sampled)); + let c = work.px(x, y); + if c[a] > 0.0 { + weight[i] = match_w(dist(&c[..nc], &sampled)); } - weight[(y - r.y0) as usize * w + (x - r.x0) as usize] = match_w(dist(c, &sampled)); } } if limits != Limits::Discontiguous { - keep_connected(&mut weight, w, h, (cx.clamp(r.x0, r.x1 - 1) - r.x0) as usize, (cy.clamp(r.y0, r.y1 - 1) - r.y0) as usize); + keep_connected(&mut reach, w, h, (cx.clamp(r.x0, r.x1 - 1) - r.x0) as usize, (cy.clamp(r.y0, r.y1 - 1) - r.y0) as usize); + for (wv, rv) in weight.iter_mut().zip(&reach) { + if *rv <= 0.0 { + *wv = 0.0; + } + } } for y in r.y0..r.y1 { for x in r.x0..r.x1 { @@ -145,16 +208,32 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option [f32; 4] { + [200.0 / 255.0, (40.0 + 20.0 * i as f32) / 255.0, 40.0 / 255.0, 1.0] +} + +/// Eight 100 px blocks side by side, 900 x 300; the reference's drag row y 450 is y 150 here. +fn blocks(fmt: PixelFormat) -> Surface { + let mut s = Surface::new(fmt); + for i in 0..8 { + let x = 100 * i as i32; + s.fill_rect(Rect::new(x, 0, x + 100, 300), &from_rgba(&fmt, block(i))); + } + s +} + +fn stroke(points: &[(f64, f64)]) -> Stroke { + Stroke { + brush: BrushSettings { size: 40.0, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() }, + points: points.iter().map(|&(x, y)| StrokePoint::new(x, y, 1.0)).collect(), + } +} + +fn once(tolerance_percent: f32) -> BgEraseSettings { + BgEraseSettings { sampling: Sampling::Once, limits: Limits::Discontiguous, tolerance: tolerance_percent / 100.0, ..Default::default() } +} + +fn swatch(tolerance_percent: f32) -> BgEraseSettings { + BgEraseSettings { sampling: Sampling::BackgroundSwatch, background: block(0), ..once(tolerance_percent) } +} + +/// RGBA 0-255 at block `i`'s centre. +fn rgba(s: &Surface, i: usize) -> [i32; 4] { + let p = s.rgba(100 * i as i32 + 50, 150); + p.map(|v| (v * 255.0).round() as i32) +} + +/// The reference's drag from block 0's centre to `to_x`, Sampling Once. +fn drag(fmt: PixelFormat, tolerance_percent: f32, to_x: f64) -> Surface { + let mut s = blocks(fmt); + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (to_x, 150.0)]), &once(tolerance_percent), None); + s +} + +/// Separate single-click strokes on every block centre, `clicks` times, Background Swatch. +fn clicks(fmt: PixelFormat, tolerance_percent: f32, clicks: usize) -> Surface { + let mut s = blocks(fmt); + for _ in 0..clicks { + for i in 0..8 { + apply_background_eraser(&mut s, &stroke(&[(100.0 * i as f64 + 50.0, 150.0)]), &swatch(tolerance_percent), None); + } + } + s +} + +fn assert_alpha_row(s: &Surface, want: &[i32], what: &str) { + let got: Vec = (0..want.len()).map(|i| rgba(s, i)[3]).collect(); + for (i, (g, w)) in got.iter().zip(want).enumerate() { + assert!((g - w).abs() <= 8, "{what}: block {i} alpha {g}, measured {w} (row {got:?})"); + } +} + +#[test] +fn the_eight_block_drag_gives_the_measured_rgba() { + const WANT: [[i32; 4]; 8] = [ + [200, 40, 40, 0], + [200, 216, 40, 29], + [200, 184, 40, 71], + [200, 175, 40, 113], + [200, 172, 40, 155], + [200, 170, 40, 196], + [200, 169, 40, 238], + [200, 180, 40, 255], + ]; + let s = drag(PixelFormat::RGBA8, 50.0, 750.0); + for (i, want) in WANT.iter().enumerate() { + let got = rgba(&s, i); + // Block 0 is fully erased: only its alpha is defined. + let channels = if want[3] == 0 { 3..4 } else { 0..4 }; + for c in channels { + assert!((got[c] - want[c]).abs() <= 8, "block {i}: got {got:?}, measured {want:?}"); + } + } +} + +#[test] +fn the_drag_table_of_11901_holds_with_decontamination() { + let rows: [(f32, [i32; 8]); 5] = [ + (10.0, [0, 194, 255, 255, 255, 255, 255, 255]), + (20.0, [0, 90, 197, 255, 255, 255, 255, 255]), + (30.0, [0, 56, 126, 196, 255, 255, 255, 255]), + (50.0, [0, 30, 75, 114, 156, 198, 238, 255]), + (70.0, [0, 18, 48, 78, 107, 137, 167, 197]), + ]; + for (tol, want) in rows { + assert_alpha_row(&drag(PixelFormat::RGBA8, tol, 750.0), &want, &format!("drag at Tolerance {tol}")); + } + // At Tolerance 100 the decontaminated colours stay inside the Tolerance, so every dab erases + // a bit more; the drag on to 790 is the measured row (block 7 is no reference at 750). + assert_alpha_row(&drag(PixelFormat::RGBA8, 100.0, 790.0), &[0, 7, 19, 32, 44, 56, 68, 81], "drag at Tolerance 100"); +} + +#[test] +fn later_strokes_match_the_decontaminated_colour() { + let fmt = PixelFormat::RGBA8; + assert_alpha_row(&clicks(fmt, 100.0, 1), &[0, 12, 33, 54, 74, 95, 116, 136], "Tolerance 100, 1 click"); + assert_alpha_row(&clicks(fmt, 100.0, 2), &[0, 10, 28, 45, 62, 80, 97, 114], "Tolerance 100, 2 clicks"); + assert_alpha_row(&clicks(fmt, 100.0, 3), &[0, 8, 23, 38, 52, 67, 81, 96], "Tolerance 100, 3 clicks"); + // At Tolerance 50 the decontaminated colours are outside the Tolerance: a second click leaves + // the block centres as they were. + let one = clicks(fmt, 50.0, 1); + assert_alpha_row(&one, &[0, 29, 71, 113, 155, 196, 238, 255], "Tolerance 50, 1 click"); + let two = clicks(fmt, 50.0, 2); + for i in 1..8 { + assert_eq!(rgba(&two, i), rgba(&one, i), "Tolerance 50, 2 clicks: block {i}"); + } +} + +#[test] +fn partly_erased_pixels_composite_back_to_their_original_colour() { + // Composited over the sampled colour, each partly erased block centre gives back its original + // colour within 2 levels, after one click and after the drag. + for s in [clicks(PixelFormat::RGBA8, 50.0, 1), drag(PixelFormat::RGBA8, 50.0, 750.0)] { + for i in 1..7 { + let [r, g, b, a] = rgba(&s, i); + assert!(a > 0 && a < 255, "block {i} partly erased, alpha {a}"); + let over = |c: i32, s: i32| (c * a + s * (255 - a)) as f32 / 255.0; + let orig = block(i).map(|v| v * 255.0); + for (k, (got, want)) in [over(r, 200), over(g, 40), over(b, 40)].iter().zip(orig).enumerate() { + assert!((got - want).abs() <= 2.0, "block {i} channel {k}: composite {got}, original {want}"); + } + } + } +} + +#[test] +fn kept_and_erased_pixels_and_the_channel_range() { + let s = drag(PixelFormat::RGBA8, 50.0, 750.0); + // Fully kept: the colour exactly; outside the brush: untouched. + assert_eq!(rgba(&s, 7), [200, 180, 40, 255]); + assert_eq!(s.rgba(350, 10), blocks(PixelFormat::RGBA8).rgba(350, 10)); + // Fully erased: alpha 0. + assert_eq!(rgba(&s, 0)[3], 0); + // At Tolerance 100 the decontaminated green clips at 255 rather than wrapping, and 32-bit + // float results stay finite and within 0..1 for in-range colours. + let t = clicks(PixelFormat::RGBA8, 100.0, 1); + assert_eq!(rgba(&t, 7)[1], 255, "clipped, not wrapped"); + let f = clicks(PixelFormat::RGBA32F, 100.0, 3); + for x in (0..900).step_by(7) { + for v in f.rgba(x, 150) { + assert!(v.is_finite() && (0.0..=1.0).contains(&v), "x {x}: {v}"); + } + } +} + +#[test] +fn it_works_in_the_documents_own_channels() { + // 16-bit RGB: the same RGBA as 8-bit. + let rgb16 = PixelFormat::new(ColorMode::Rgb, SampleType::U16, true); + let a = drag(PixelFormat::RGBA8, 50.0, 750.0); + let b = drag(rgb16, 50.0, 750.0); + for i in 0..8 { + let (x, y) = (rgba(&a, i), rgba(&b, i)); + for c in 0..4 { + assert!((x[c] - y[c]).abs() <= 2 || x[3] == 0, "16-bit block {i}: {y:?} against 8-bit {x:?}"); + } + } + // Gray (8 and 16 bit): the gray level is decontaminated the same way, so the composite over + // the sampled gray gives back the original level, and a second click at Tolerance 50 changes + // nothing at the block centres. + for sample in [SampleType::U8, SampleType::U16] { + let gray = PixelFormat::new(ColorMode::Grayscale, sample, true); + let level = |i: usize| (40.0 + 20.0 * i as f32) / 255.0; + let mut s = Surface::new(gray); + for i in 0..8 { + let x = 100 * i as i32; + s.fill_rect(Rect::new(x, 0, x + 100, 300), &[level(i), 1.0]); + } + let bs = BgEraseSettings { background: [level(0), level(0), level(0), 1.0], ..swatch(50.0) }; + let click_all = |s: &mut Surface| { + for i in 0..8 { + apply_background_eraser(s, &stroke(&[(100.0 * i as f64 + 50.0, 150.0)]), &bs, None); + } + }; + click_all(&mut s); + let first = s.clone(); + for i in 1..7 { + let p = s.pixel(100 * i as i32 + 50, 150); + let (v, a) = (p[0], p[1]); + assert!(a > 0.0 && a < 1.0, "{sample:?} block {i} partly erased, alpha {a}"); + let over = v * a + level(0) * (1.0 - a); + assert!((over - level(i)).abs() <= 2.0 / 255.0, "{sample:?} block {i}: composite {over}, original {}", level(i)); + } + click_all(&mut s); + for i in 1..8 { + let at = (100 * i + 50, 150); + assert_eq!(s.pixel(at.0, at.1), first.pixel(at.0, at.1), "{sample:?} block {i}: a second click at Tolerance 50 changes nothing"); + } + } +} diff --git a/crates/paint/src/bg_erase_find_edges_tests.rs b/crates/paint/src/bg_erase_find_edges_tests.rs new file mode 100644 index 0000000000..ee95dd8c2e --- /dev/null +++ b/crates/paint/src/bg_erase_find_edges_tests.rs @@ -0,0 +1,101 @@ +//! Background Eraser Limits Find Edges (#11904): a blurred edge is erased graded, keeping at least +//! as much of the transition as Contiguous does, instead of cut hard at the Tolerance. Expected +//! values are the reference application's measurements from the issue (8-bit RGB, 40 px and 60 px +//! hard round tips, Tolerance 50, Sampling Continuous). + +use photocraft_color::PixelFormat; +use photocraft_geom::Rect; +use photocraft_raster::{Surface, from_rgba}; + +use crate::bg_erase::{BgEraseSettings, apply_background_eraser}; +use crate::replace::{Limits, Sampling}; +use crate::{BrushSettings, Stroke, StrokePoint}; + +/// Measured red channel along y 70 from x 185 across the 4 px Gaussian red|green edge at x 200. +const RED: [i32; 30] = [220, 220, 220, 220, 219, 219, 217, 214, 210, 203, 194, 182, 168, 152, 134, 116, 98, 82, 68, 56, 47, 40, 36, 33, 31, 31, 30, 30, 30, 30]; +/// Alpha along y 70 from x 185 after a click at 190,70. +const FIND_EDGES: [i32; 15] = [8, 8, 8, 4, 4, 0, 0, 0, 17, 42, 76, 121, 176, 238, 255]; +const CONTIGUOUS: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 4, 21, 46, 79, 123, 178, 238, 255]; + +fn rgb(c: [i32; 3]) -> [f32; 4] { + [c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0] +} + +/// The issue's test layer: red | green | blue | pink stripes (y 0-300), a white gap at y 140-160 +/// across the red stripe, and the red|green edge blurred over y 0-130. A Gaussian blur mixes every +/// channel with the same weights, so green and blue follow red's mix fraction. +fn layer() -> Surface { + let fmt = PixelFormat::RGBA8; + let mut s = Surface::new(fmt); + for (x0, c) in [(0, [220, 30, 30]), (200, [30, 180, 60]), (400, [40, 60, 220]), (600, [240, 120, 120])] { + s.fill_rect(Rect::new(x0, 0, x0 + 200, 300), &from_rgba(&fmt, rgb(c))); + } + s.fill_rect(Rect::new(0, 140, 200, 160), &from_rgba(&fmt, rgb([255, 255, 255]))); + for (i, r) in RED.iter().enumerate() { + let t = (220 - r) as f32 / 190.0; + let c = [*r as f32 / 255.0, (30.0 + 150.0 * t) / 255.0, (30.0 + 30.0 * t) / 255.0, 1.0]; + let x = 185 + i as i32; + s.fill_rect(Rect::new(x, 0, x + 1, 130), &from_rgba(&fmt, c)); + } + s +} + +fn click(at: (f64, f64), size: f32, limits: Limits) -> Surface { + let mut s = layer(); + let stroke = Stroke { + brush: BrushSettings { size, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() }, + points: vec![StrokePoint::new(at.0, at.1, 1.0)], + }; + let bs = BgEraseSettings { sampling: Sampling::Continuous, limits, tolerance: 0.5, ..Default::default() }; + apply_background_eraser(&mut s, &stroke, &bs, None); + s +} + +fn alpha(s: &Surface, x: i32, y: i32) -> i32 { + (s.rgba(x, y)[3] * 255.0).round() as i32 +} + +#[test] +fn find_edges_grades_a_blurred_edge_instead_of_cutting_it() { + let fe = click((190.0, 70.0), 40.0, Limits::FindEdges); + let co = click((190.0, 70.0), 40.0, Limits::Contiguous); + for (i, want) in FIND_EDGES.iter().enumerate() { + let x = 185 + i as i32; + let (f, c) = (alpha(&fe, x, 70), alpha(&co, x, 70)); + assert!((f - want).abs() <= 10, "x {x}: Find Edges alpha {f}, measured {want}"); + assert!(f >= c, "x {x}: Find Edges keeps {f}, less than Contiguous's {c}"); + } + // Past the transition nothing is erased (before, Find Edges cut through x 201). + for x in 200..230 { + assert_eq!(alpha(&fe, x, 70), 255, "x {x}"); + } +} + +#[test] +fn find_edges_on_a_hard_edge_gives_the_contiguous_result() { + // 60 px tip at 100,138 on red just above the white gap: column x 100 erased through y 139, the + // gap and the red below it kept. + let fe = click((100.0, 138.0), 60.0, Limits::FindEdges); + let co = click((100.0, 138.0), 60.0, Limits::Contiguous); + for y in 100..176 { + assert_eq!(alpha(&fe, 100, y), alpha(&co, 100, y), "y {y}"); + } + for y in 110..140 { + assert_eq!(alpha(&fe, 100, y), 0, "red above the gap, y {y}"); + } + for y in 140..176 { + assert_eq!(alpha(&fe, 100, y), 255, "the gap and the red below it, y {y}"); + } +} + +#[test] +fn contiguous_and_discontiguous_keep_their_results() { + // This item changes only Find Edges: the other two limits still give the measured row. + for limits in [Limits::Contiguous, Limits::Discontiguous] { + let s = click((190.0, 70.0), 40.0, limits); + for (i, want) in CONTIGUOUS.iter().enumerate() { + let x = 185 + i as i32; + assert!((alpha(&s, x, 70) - want).abs() <= 8, "{limits:?} x {x}: {} against {want}", alpha(&s, x, 70)); + } + } +} diff --git a/crates/paint/src/bg_erase_graded_alpha_tests.rs b/crates/paint/src/bg_erase_graded_alpha_tests.rs new file mode 100644 index 0000000000..51e1bbc20d --- /dev/null +++ b/crates/paint/src/bg_erase_graded_alpha_tests.rs @@ -0,0 +1,177 @@ +//! Background Eraser graded alpha (#11901): one dab erases a colour less the further it is from the +//! sampled colour, over the whole Tolerance, not fully up to the Tolerance. Expected values are the +//! reference application's single-click measurements from the issue (8-bit RGB, 40 px hard round +//! tip, Sampling Background Swatch with background (200,40,40), alpha at the patch centre). + +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_geom::Rect; +use photocraft_raster::{Surface, from_rgba}; + +use crate::bg_erase::{BgEraseSettings, apply_background_eraser}; +use crate::replace::{Limits, Sampling}; +use crate::{BrushSettings, Stroke, StrokePoint}; + +/// The sampled colour of every measurement: (200,40,40). +const SAMPLE: [i32; 3] = [200, 40, 40]; + +/// Allowed deviation from the measured alpha ("within 8 levels"). +const LEVELS: i32 = 8; + +fn rgb(c: [i32; 3]) -> [f32; 4] { + [c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0] +} + +fn click(at: (f64, f64)) -> Stroke { + Stroke { + brush: BrushSettings { size: 40.0, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() }, + points: vec![StrokePoint::new(at.0, at.1, 1.0)], + } +} + +fn swatch(tolerance_percent: f32, background: [f32; 4]) -> BgEraseSettings { + BgEraseSettings { + sampling: Sampling::BackgroundSwatch, + limits: Limits::Discontiguous, + tolerance: tolerance_percent / 100.0, + background, + ..Default::default() + } +} + +/// One click in the centre of a 100 px patch of `colour` (straight RGBA) in `fmt`; alpha 0-255 at +/// the centre. +fn one_click(fmt: PixelFormat, colour: [f32; 4], bs: &BgEraseSettings) -> i32 { + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(0, 0, 100, 100), &from_rgba(&fmt, colour)); + apply_background_eraser(&mut s, &click((50.0, 50.0)), bs, None); + (s.rgba(50, 50)[3] * 255.0).round() as i32 +} + +/// The measured single-click table: (Tolerance, [(green difference d, alpha)]). +fn single_click_table() -> Vec<(f32, Vec<(i32, i32)>)> { + vec![ + (10.0, vec![(10, 92), (20, 194), (30, 255), (40, 255)]), + (30.0, vec![(10, 21), (20, 56), (30, 91), (40, 126), (50, 161), (60, 196), (80, 255), (100, 255)]), + (50.0, vec![(10, 8), (20, 29), (30, 50), (40, 71), (50, 92), (60, 113), (80, 155), (100, 196), (120, 238), (140, 255)]), + (70.0, vec![(10, 3), (20, 18), (30, 33), (40, 48), (50, 63), (60, 78), (80, 107), (100, 137), (120, 167), (140, 197), (160, 227)]), + (100.0, vec![(10, 2), (20, 12), (30, 23), (40, 33), (50, 43), (60, 54), (80, 74), (100, 95), (120, 116), (140, 136), (160, 157)]), + ] +} + +fn assert_near(got: i32, want: i32, what: &str) { + assert!((got - want).abs() <= LEVELS, "{what}: got alpha {got}, measured {want}"); +} + +#[test] +fn one_click_falls_off_over_the_whole_tolerance() { + let bs = |tol| swatch(tol, rgb(SAMPLE)); + for (tol, row) in single_click_table() { + for (d, want) in row { + let got = one_click(PixelFormat::RGBA8, rgb([SAMPLE[0], SAMPLE[1] + d, SAMPLE[2]]), &bs(tol)); + assert_near(got, want, &format!("Tolerance {tol}, green +{d}")); + } + } +} + +#[test] +fn same_sign_differences_count_once_and_opposite_signs_add_up() { + // Measured at Tolerance 50, single clicks, sample (200,40,40): (difference per channel, alpha). + let rows: [([i32; 3], i32); 15] = [ + ([0, 20, 0], 29), + ([-20, 0, 0], 29), + ([0, 0, 20], 29), + ([0, 20, 20], 29), + ([0, 40, 20], 71), + ([0, 20, 40], 71), + ([0, 60, 20], 113), + ([-20, 20, 0], 71), + ([-40, 40, 0], 155), + ([-60, 60, 0], 238), + ([10, 10, 10], 8), + ([20, 20, 20], 29), + ([40, 40, 40], 71), + ([-10, -10, -10], 8), + ([-40, -40, -40], 71), + ]; + let bs = swatch(50.0, rgb(SAMPLE)); + for (diff, want) in rows { + let colour = [SAMPLE[0] + diff[0], SAMPLE[1] + diff[1], SAMPLE[2] + diff[2]]; + assert_near(one_click(PixelFormat::RGBA8, rgb(colour), &bs), want, &format!("difference {diff:?}")); + } +} + +#[test] +fn a_blurred_edge_keeps_its_transition_graded() { + // Red (220,30,30) | green (30,180,60) at x 200, blurred with a 4 px Gaussian; the measured red + // channel along y 70 from x 185. A Gaussian blur mixes every channel with the same weights, so + // green and blue follow red's mix fraction. + const RED: [i32; 30] = + [220, 220, 220, 220, 219, 219, 217, 214, 210, 203, 194, 182, 168, 152, 134, 116, 98, 82, 68, 56, 47, 40, 36, 33, 31, 31, 30, 30, 30, 30]; + const ALPHA: [i32; 15] = [0, 0, 0, 0, 0, 0, 0, 4, 21, 46, 79, 123, 178, 238, 255]; + let fmt = PixelFormat::RGBA8; + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(0, 0, 185, 140), &from_rgba(&fmt, rgb([220, 30, 30]))); + s.fill_rect(Rect::new(215, 0, 400, 140), &from_rgba(&fmt, rgb([30, 180, 60]))); + for (i, r) in RED.iter().enumerate() { + let t = (220 - r) as f32 / 190.0; + let c = [*r as f32 / 255.0, (30.0 + 150.0 * t) / 255.0, (30.0 + 30.0 * t) / 255.0, 1.0]; + let x = 185 + i as i32; + s.fill_rect(Rect::new(x, 0, x + 1, 140), &from_rgba(&fmt, c)); + } + for limits in [Limits::Contiguous, Limits::Discontiguous] { + let mut t = s.clone(); + let bs = BgEraseSettings { sampling: Sampling::Once, limits, tolerance: 0.5, ..Default::default() }; + apply_background_eraser(&mut t, &click((190.0, 70.0)), &bs, None); + for (i, want) in ALPHA.iter().enumerate() { + let x = 185 + i as i32; + let got = (t.rgba(x, 70)[3] * 255.0).round() as i32; + assert_near(got, *want, &format!("{limits:?} x {x}")); + } + for x in 200..215 { + assert_eq!(t.rgba(x, 70)[3], 1.0, "{limits:?} x {x} beyond the Tolerance kept"); + } + } +} + +#[test] +fn an_exact_match_is_erased_and_far_colours_are_kept_at_every_tolerance() { + for tol in [0.0, 1.0, 10.0, 30.0, 50.0, 70.0, 100.0] { + let bs = swatch(tol, rgb(SAMPLE)); + assert_eq!(one_click(PixelFormat::RGBA8, rgb(SAMPLE), &bs), 0, "Tolerance {tol}: the sample itself"); + if tol < 100.0 { + // Opposite-sign differences of 255 + 215: beyond every Tolerance below 100 %. + assert_eq!(one_click(PixelFormat::RGBA8, rgb([0, 255, 40]), &bs), 255, "Tolerance {tol}: a far colour"); + } + } + // Tolerance 0 erases nothing but the exact colour. + assert_eq!(one_click(PixelFormat::RGBA8, rgb([200, 41, 40]), &swatch(0.0, rgb(SAMPLE))), 255); +} + +#[test] +fn the_distance_is_measured_in_the_documents_own_channels() { + // 16-bit RGB: the same single-click table as 8-bit. + let rgb16 = PixelFormat::new(ColorMode::Rgb, SampleType::U16, true); + for (tol, row) in single_click_table() { + for (d, want) in row { + let got = one_click(rgb16, rgb([SAMPLE[0], SAMPLE[1] + d, SAMPLE[2]]), &swatch(tol, rgb(SAMPLE))); + assert_near(got, want, &format!("16-bit Tolerance {tol}, green +{d}")); + } + } + // Gray (8 and 16 bit): the distance is the absolute difference of the gray levels, so a gray + // patch d levels from the swatch erases like a one-channel difference of d in RGB, either way. + for sample in [SampleType::U8, SampleType::U16] { + let gray = PixelFormat::new(ColorMode::Grayscale, sample, true); + let level = |v: i32| [v as f32 / 255.0, v as f32 / 255.0, v as f32 / 255.0, 1.0]; + for (tol, row) in single_click_table() { + for (d, want) in row { + let bs = swatch(tol, level(60)); + if 60 + d <= 255 { + assert_near(one_click(gray, level(60 + d), &bs), want, &format!("{sample:?} gray Tolerance {tol}, +{d}")); + } + if d <= 60 { + assert_near(one_click(gray, level(60 - d), &bs), want, &format!("{sample:?} gray Tolerance {tol}, -{d}")); + } + } + } + } +} diff --git a/crates/paint/src/bg_erase_protect_foreground_tests.rs b/crates/paint/src/bg_erase_protect_foreground_tests.rs new file mode 100644 index 0000000000..4f0cf43915 --- /dev/null +++ b/crates/paint/src/bg_erase_protect_foreground_tests.rs @@ -0,0 +1,236 @@ +//! Protect Foreground Color (#11903): the protection fades with the distance from the foreground +//! colour, so the sampled colour is still erased while colours at and beyond the foreground are kept. + +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_geom::Rect; +use photocraft_raster::{Surface, from_rgba}; + +use crate::bg_erase::{BgEraseSettings, apply_background_eraser}; +use crate::replace::{Limits, Sampling}; +use crate::{BrushSettings, Stroke, StrokePoint}; + +/// Block `i` of the reference test layer: (200, 40 + 20 i, 40), so block i differs from block 0 +/// by 20 i in green only. +fn block(i: usize) -> [f32; 4] { + [200.0 / 255.0, (40.0 + 20.0 * i as f32) / 255.0, 40.0 / 255.0, 1.0] +} + +/// Eight 100 px blocks side by side, 900 x 300 (the reference's layout, shifted up). +fn blocks(fmt: PixelFormat) -> Surface { + let mut s = Surface::new(fmt); + for i in 0..8 { + let x = 100 * i as i32; + s.fill_rect(Rect::new(x, 0, x + 100, 300), &from_rgba(&fmt, block(i))); + } + s +} + +fn stroke(points: &[(f64, f64)]) -> Stroke { + Stroke { + brush: BrushSettings { size: 40.0, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() }, + points: points.iter().map(|&(x, y)| StrokePoint::new(x, y, 1.0)).collect(), + } +} + +fn settings(protect: Option) -> BgEraseSettings { + BgEraseSettings { + sampling: Sampling::Once, + limits: Limits::Discontiguous, + tolerance: 0.5, + protect_foreground: protect.is_some(), + foreground: block(protect.unwrap_or(0)), + ..Default::default() + } +} + +/// The reference's drag from block 0's centre through all eight, with `bs`; alpha (0-255) at each +/// centre. +fn drag_with(fmt: PixelFormat, bs: &BgEraseSettings) -> [i32; 8] { + let mut s = blocks(fmt); + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), bs, None); + std::array::from_fn(|i| (s.rgba(100 * i as i32 + 50, 150)[3] * 255.0).round() as i32) +} + +/// The reference's drag with the foreground at block `protect` (protection off for `None`). +fn drag(fmt: PixelFormat, protect: Option) -> [i32; 8] { + drag_with(fmt, &settings(protect)) +} + +/// Allowed deviation from the measured alpha ("within 8 levels"). +const LEVELS: i32 = 8; + +fn assert_near(got: [i32; 8], want: [i32; 8], what: &str) { + for i in 0..8 { + assert!((got[i] - want[i]).abs() <= LEVELS, "{what}: block {i}, got {got:?}, reference {want:?}"); + } +} + +/// The measured rows: Sampling Once, Discontiguous, Tolerance 50, 40 px hard tip. +const REFERENCE: [(usize, [i32; 8]); 3] = + [(1, [0, 255, 255, 255, 255, 255, 255, 255]), (3, [0, 76, 166, 255, 255, 255, 255, 255]), (5, [0, 40, 94, 148, 201, 255, 255, 255])]; + +/// The same drag without protection in the reference (the graded erase of #11901). +const UNPROTECTED: [i32; 8] = [0, 30, 75, 114, 156, 198, 238, 255]; + +#[test] +fn the_sampled_colour_is_erased_and_colours_from_the_foreground_on_are_kept() { + for (fg, want) in REFERENCE { + let got = drag(PixelFormat::RGBA8, Some(fg)); + assert_near(got, want, &format!("fg block {fg}")); + for i in 0..8 { + // Fully kept and fully erased blocks match exactly. + if want[i] == 255 || want[i] == 0 { + assert_eq!(got[i], want[i], "fg block {fg}: block {i}, got {got:?}"); + } + } + } +} + +#[test] +fn a_foreground_off_in_two_channels_narrows_by_the_sample_distance() { + // Measured with the same drag: the Tolerance narrows to the foreground's distance from the + // sample (200,40,40) as the sample match measures it, the largest increase plus the largest + // decrease over the channels, not the largest per-channel difference. + let rows: [([i32; 3], [i32; 8]); 4] = [ + // Red -100, green +100: 200 levels away, beyond Tolerance 50, so nothing is protected + // (the largest per-channel difference, 100, would keep blocks 5 to 7). + ([100, 140, 40], [0, 32, 75, 112, 156, 196, 238, 255]), + // Red -50, green +50: 100 levels, like the foreground at block 5. + ([150, 90, 40], [0, 40, 94, 153, 201, 255, 255, 255]), + // Two increases, the larger 50: 50 levels. + ([230, 90, 40], [0, 101, 203, 255, 255, 255, 255, 255]), + ([200, 90, 70], [0, 98, 202, 255, 255, 255, 255, 255]), + ]; + for (fg, want) in rows { + let foreground = [fg[0] as f32 / 255.0, fg[1] as f32 / 255.0, fg[2] as f32 / 255.0, 1.0]; + let got = drag_with(PixelFormat::RGBA8, &BgEraseSettings { foreground, ..settings(Some(0)) }); + assert_near(got, want, &format!("fg {fg:?}")); + assert_eq!(got[0], 0, "fg {fg:?}: the sample erased, got {got:?}"); + } +} + +#[test] +fn protection_narrows_the_tolerance_to_the_foreground_in_one_dab() { + // One click (Background Swatch = block 0, so the click's own pixel does not matter) on each + // block: with the foreground at block `fg`, the protected click erases what an unprotected + // click at Tolerance = the sample-to-foreground distance erases, and keeps block fg and beyond. + let fmt = PixelFormat::RGBA8; + let click = |protect: Option, tolerance: f32| -> Vec { + (0..8) + .map(|i| { + let mut s = blocks(fmt); + let bs = BgEraseSettings { sampling: Sampling::BackgroundSwatch, background: block(0), tolerance, ..settings(protect) }; + let x = 100.0 * i as f64 + 50.0; + apply_background_eraser(&mut s, &stroke(&[(x, 150.0)]), &bs, None); + s.rgba(x as i32, 150)[3] + }) + .collect() + }; + for fg in [1, 3, 5] { + let protected = click(Some(fg), 0.5); + let narrowed = click(None, 20.0 * fg as f32 / 255.0); + for i in 0..8 { + if i < fg { + assert!((protected[i] - narrowed[i]).abs() <= 1.0 / 255.0, "fg block {fg}: block {i} {protected:?} vs {narrowed:?}"); + } else { + assert_eq!(protected[i], 1.0, "fg block {fg}: block {i} kept, {protected:?}"); + } + } + } +} + +#[test] +fn a_foreground_equal_to_the_sample_erases_nothing() { + for limits in [Limits::Contiguous, Limits::Discontiguous, Limits::FindEdges] { + for tolerance in [0.0, 0.1, 0.5, 1.0] { + let s = blocks(PixelFormat::RGBA8); + let mut t = s.clone(); + let bs = BgEraseSettings { limits, tolerance, ..settings(Some(0)) }; + apply_background_eraser(&mut t, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &bs, None); + assert_eq!(t, s, "{limits:?} tolerance {tolerance}"); + } + } +} + +#[test] +fn find_edges_keeps_the_foreground_colour_itself() { + // Find Edges grades like Contiguous (#11904); a pixel exactly at the foreground stays. + let fmt = PixelFormat::RGBA8; + let mut s = blocks(fmt); + let bs = BgEraseSettings { limits: Limits::FindEdges, ..settings(Some(1)) }; + apply_background_eraser(&mut s, &stroke(&[(80.0, 150.0), (120.0, 150.0)]), &bs, None); + assert_eq!(s.rgba(75, 150)[3], 0.0, "the sample erased"); + assert_eq!(s.rgba(110, 150)[3], 1.0, "the foreground colour kept"); +} + +#[test] +fn protect_off_is_unchanged() { + // The drag without protection: the reference's row, which the protection change leaves alone. + assert_near(drag(PixelFormat::RGBA8, None), UNPROTECTED, "protection off"); + let mut s = blocks(PixelFormat::RGBA8); + let mut t = s.clone(); + let on_far = BgEraseSettings { foreground: [0.0, 0.0, 1.0, 1.0], protect_foreground: true, ..settings(None) }; + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &settings(None), None); + apply_background_eraser(&mut t, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &on_far, None); + assert_eq!(s, t, "a foreground beyond the Tolerance protects nothing"); +} + +#[test] +fn protection_works_in_the_documents_own_channels() { + // 16-bit RGB: the same rows as 8-bit. + let rgb16 = PixelFormat::new(ColorMode::Rgb, SampleType::U16, true); + for (fg, want) in REFERENCE { + assert_near(drag(rgb16, Some(fg)), want, &format!("16-bit fg block {fg}")); + } + // Gray: blocks stepping by 20 in gray; foreground at block 3 keeps blocks 3 and beyond and + // still erases block 0. + let gray = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, true); + let mut s = Surface::new(gray); + let level = |i: usize| (40.0 + 20.0 * i as f32) / 255.0; + for i in 0..8 { + let x = 100 * i as i32; + s.fill_rect(Rect::new(x, 0, x + 100, 300), &[level(i), 1.0]); + } + let fg = [level(3), level(3), level(3), 1.0]; + let bs = BgEraseSettings { foreground: fg, ..settings(Some(3)) }; + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &bs, None); + let a: Vec = (0..8).map(|i| s.rgba(100 * i + 50, 150)[3]).collect(); + assert_eq!(a[0], 0.0, "gray: the sample erased, {a:?}"); + for (i, v) in a.iter().enumerate().skip(3) { + assert_eq!(*v, 1.0, "gray: block {i} kept, {a:?}"); + } +} + +#[test] +fn the_foreground_is_matched_at_the_documents_precision() { + // Mid grey 0.5 lies between two 8-bit (and 16-bit) levels and is stored one level up, nearer + // white. The stored foreground colour must still count as the foreground, and a foreground + // that is stored as the sampled colour must still protect everything. + let grey = [0.5, 0.5, 0.5, 1.0]; + for mode in [ColorMode::Rgb, ColorMode::Grayscale] { + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let fmt = PixelFormat::new(mode, sample, true); + let bs = BgEraseSettings { + sampling: Sampling::Once, + limits: Limits::FindEdges, + tolerance: 1.0, + protect_foreground: true, + foreground: grey, + ..Default::default() + }; + // White (the sample) next to the foreground grey. + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(0, 0, 100, 100), &from_rgba(&fmt, [1.0; 4])); + s.fill_rect(Rect::new(100, 0, 200, 100), &from_rgba(&fmt, grey)); + apply_background_eraser(&mut s, &stroke(&[(50.0, 50.0), (150.0, 50.0)]), &bs, None); + assert_eq!(s.rgba(50, 50)[3], 0.0, "{fmt:?}: the sample erased"); + assert_eq!(s.rgba(150, 50)[3], 1.0, "{fmt:?}: the stored foreground colour kept"); + // The foreground grey is also the sample. + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(0, 0, 200, 100), &from_rgba(&fmt, grey)); + let t = s.clone(); + apply_background_eraser(&mut s, &stroke(&[(50.0, 50.0), (150.0, 50.0)]), &bs, None); + assert_eq!(s, t, "{fmt:?}: a foreground stored as the sample erases nothing"); + } + } +} diff --git a/crates/paint/src/replace.rs b/crates/paint/src/replace.rs index 20619cd48a..c4157fac81 100644 --- a/crates/paint/src/replace.rs +++ b/crates/paint/src/replace.rs @@ -96,6 +96,14 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut ReplaceMode::Luminosity => BlendMode::Luminosity, }; let fg = [rs.color[0], rs.color[1], rs.color[2]]; + // In a Lab/8 document Color mode keeps the pixel's L and takes the foreground's a and b, as in + // the reference application (#11922): the stored a, b channels move straight to its. Lab/16 + // wasn't measured and keeps the RGB blend. + let lab_color = fmt.mode == photocraft_color::ColorMode::Lab && fmt.sample == photocraft_color::SampleType::U8 && rs.mode == ReplaceMode::Color; + let fg_ab = { + let l = photocraft_color::convert::srgb_to_lab(fg); + [(l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0] + }; let tol = rs.tolerance.clamp(0.0, 1.0); let soft = rs.anti_alias && rs.limits != Limits::FindEdges; let mut once: Option<[f32; 3]> = None; @@ -189,6 +197,11 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut continue; } let px = work.px_mut(x, y); + if lab_color { + px[1] += (fg_ab[0] - px[1]) * k; + px[2] += (fg_ab[1] - px[2]) * k; + continue; + } let c = to_rgba(&fmt, px); let b = blend_rgb(mode, [c[0], c[1], c[2]], fg); let o = [c[0] + (b[0] - c[0]) * k, c[1] + (b[1] - c[1]) * k, c[2] + (b[2] - c[2]) * k, c[3]]; @@ -199,6 +212,10 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut } } +#[cfg(test)] +#[path = "replace_lab_tests.rs"] +mod replace_lab_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/paint/src/replace_lab_tests.rs b/crates/paint/src/replace_lab_tests.rs new file mode 100644 index 0000000000..caf024fb40 --- /dev/null +++ b/crates/paint/src/replace_lab_tests.rs @@ -0,0 +1,100 @@ +//! #11922: in a Lab document, Color mode keeps the pixel's L and takes the foreground's a and b. +//! The setup is the issue's: red, green and pink stripes and the darker block (200,40,40), a blue +//! foreground, a 40 px hard tip, one click on each. Hue, Saturation and Luminosity keep today's RGB +//! blend. + +use photocraft_color::{ColorMode, PixelFormat, SampleType}; + +use super::*; +use crate::{BrushSettings, StrokePoint}; + +const LAB8: PixelFormat = PixelFormat { mode: ColorMode::Lab, sample: SampleType::U8, alpha: true }; +const COLOURS: [[u8; 3]; 4] = [[220, 30, 30], [30, 180, 60], [240, 120, 120], [200, 40, 40]]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; + +/// A Lab/8 surface with the four colours in 100 px columns. +fn target() -> Surface { + target_in(LAB8) +} + +fn target_in(fmt: PixelFormat) -> Surface { + let mut s = Surface::new(fmt); + for (i, c) in COLOURS.iter().enumerate() { + let rgba = [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0]; + let x0 = i as i32 * 100; + s.fill_rect(Rect::new(x0, 0, x0 + 100, 100), &photocraft_raster::from_rgba(&fmt, rgba)); + } + s +} + +fn click(s: &mut Surface, mode: ReplaceMode, x: f64) { + let stroke = Stroke { + brush: BrushSettings { size: 40.0, hardness: 1.0, spacing: 0.25, pressure_size: false, ..Default::default() }, + points: vec![StrokePoint::new(x, 50.0, 1.0)], + }; + let rs = ReplaceSettings { mode, color: BLUE, ..Default::default() }; + apply_color_replacement(s, &stroke, &rs, None, false); +} + +/// The stored L (0..100) and a, b (-128..127) at a pixel. +fn lab(s: &Surface, x: i32, y: i32) -> [f32; 3] { + let px = s.pixel(x, y); + [px[0] * 100.0, px[1] * 255.0 - 128.0, px[2] * 255.0 - 128.0] +} + +#[test] +fn color_keeps_l_and_takes_the_foregrounds_a_and_b() { + let fg = photocraft_color::convert::srgb_to_lab([0.0, 0.0, 1.0]); + for i in 0..COLOURS.len() { + let mut s = target(); + let x = i as i32 * 100 + 50; + let before = lab(&s, x, 50); + click(&mut s, ReplaceMode::Color, f64::from(x) + 0.5); + let after = lab(&s, x, 50); + assert!((after[0] - before[0]).abs() <= 1.0, "colour {i}: L {} → {}", before[0], after[0]); + assert!((after[1] - fg[1]).abs() <= 2.0 && (after[2] - fg[2]).abs() <= 2.0, "colour {i}: a, b {:?} vs the foreground's {:?}", &after[1..], &fg[1..]); + // Outside the tip nothing changed. + assert_eq!(lab(&s, x - 40, 50), before, "colour {i} outside the tip"); + } +} + +#[test] +fn hue_saturation_and_luminosity_keep_todays_blend() { + for mode in [ReplaceMode::Hue, ReplaceMode::Saturation, ReplaceMode::Luminosity] { + let mut s = target(); + let pre = s.pixel(150, 50).to_vec(); + click(&mut s, mode, 150.5); + // Today's path: through RGB, blended, and back. + let blend = match mode { + ReplaceMode::Hue => BlendMode::Hue, + ReplaceMode::Saturation => BlendMode::Saturation, + _ => BlendMode::Luminosity, + }; + let c = to_rgba(&LAB8, &pre); + let b = blend_rgb(blend, [c[0], c[1], c[2]], [0.0, 0.0, 1.0]); + let want = photocraft_raster::from_rgba(&LAB8, [b[0], b[1], b[2], c[3]]); + let got = s.pixel(150, 50); + for (g, w) in got.iter().zip(&want) { + assert!((g - w).abs() <= 1.0 / 255.0 + 1e-6, "{mode:?}: {got:?} vs {want:?}"); + } + } +} + +#[test] +fn lab_16_color_keeps_todays_blend() { + // Lab/16 wasn't measured: its Color mode still blends through RGB. + let lab16 = PixelFormat { sample: SampleType::U16, ..LAB8 }; + for i in 0..COLOURS.len() { + let mut s = target_in(lab16); + let x = i as i32 * 100 + 50; + let pre = s.pixel(x, 50).to_vec(); + click(&mut s, ReplaceMode::Color, f64::from(x) + 0.5); + let c = to_rgba(&lab16, &pre); + let b = blend_rgb(BlendMode::Color, [c[0], c[1], c[2]], [0.0, 0.0, 1.0]); + let want = photocraft_raster::from_rgba(&lab16, [b[0], b[1], b[2], c[3]]); + let got = s.pixel(x, 50); + for (g, w) in got.iter().zip(&want) { + assert!((g - w).abs() <= 1.0 / 65535.0 + 1e-6, "colour {i}: {got:?} vs {want:?}"); + } + } +} diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index 133c0fa843..494a4cb6a9 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -134,7 +134,10 @@ impl Manifest { return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len()))); } let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; - let man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?; + let mut man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?; + // The name is shown as stored, so the invisible padding at its ends (white space, line breaks, + // joiners, fillers) is dropped here. + man.name = trim_name(&man.name).to_owned(); man.validate()?; Ok(man) } @@ -143,9 +146,7 @@ impl Manifest { if !valid_id(&self.id) { return Err(Error::Manifest(format!("invalid id {:?}: use 1-64 characters from A-Z a-z 0-9 . _ -", self.id))); } - let name = self.name.trim(); - let printable = name.chars().all(|c| !c.is_control() && !hidden_format(c)) && name.chars().any(visible); - if !printable || name.chars().count() > 64 { + if !printable_name(&self.name) { return Err(Error::Manifest("`name` must be 1-64 printable characters".into())); } if self.version.len() > 32 || self.description.len() > 1024 || self.author.len() > 128 { @@ -374,18 +375,23 @@ const FORMAT: &[(char, char)] = &[ ('\u{E0020}', '\u{E007F}'), ]; -/// Default-ignorable characters outside Cf (fillers, variation selectors): allowed in a name, but they -/// draw nothing on their own. +/// Default-ignorable characters outside Cf (fillers, variation selectors, unassigned ignorables), and +/// the blank Braille pattern U+2800: allowed in a name, but they draw nothing on their own. const BLANK: &[(char, char)] = &[ ('\u{34F}', '\u{34F}'), ('\u{115F}', '\u{1160}'), ('\u{17B4}', '\u{17B5}'), ('\u{180B}', '\u{180D}'), ('\u{180F}', '\u{180F}'), + ('\u{2065}', '\u{2065}'), + ('\u{2800}', '\u{2800}'), ('\u{3164}', '\u{3164}'), ('\u{FE00}', '\u{FE0F}'), ('\u{FFA0}', '\u{FFA0}'), - ('\u{E0100}', '\u{E01EF}'), + ('\u{FFF0}', '\u{FFF8}'), + ('\u{E0000}', '\u{E0000}'), + ('\u{E0002}', '\u{E001F}'), + ('\u{E0080}', '\u{E0FFF}'), ]; fn in_ranges(c: char, ranges: &[(char, char)]) -> bool { @@ -399,6 +405,85 @@ fn hidden_format(c: char) -> bool { !matches!(c, '\u{200C}' | '\u{200D}') && in_ranges(c, FORMAT) } +/// Whether `name` (already trimmed) can be shown as a label: 1-64 characters, at least one of them +/// visible, and no control characters, line or paragraph separators, or hidden format characters. +pub fn printable_name(name: &str) -> bool { + name.chars().nth(64).is_none() + && name.chars().any(visible) + && !name.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}') || hidden_format(c)) +} + +/// `name` without what pads its ends invisibly: white space, the zero-width (non-)joiners and the +/// characters that draw nothing on their own (fillers, blank Braille, unassigned ignorables, stray +/// selectors), so a name that looks like "Tone" is "Tone". What belongs to a character the name +/// keeps stays: a variation selector after it (the emoji in "Love ❤️"), and a Hangul filler that +/// is part of a syllable block (U+1160 after a leading consonant, U+115F before a vowel). +pub fn trim_name(name: &str) -> &str { + let pad = |c: char| c.is_whitespace() || matches!(c, '\u{200C}' | '\u{200D}') || in_ranges(c, BLANK); + let mut start = name.len(); + let mut chars = name.char_indices().peekable(); + while let Some((i, c)) = chars.next() { + // The choseong filler opens a syllable before a vowel, and before the jungseong filler U+1160 + // when a final consonant follows (U+115F U+1160 + a final consonant is how a lone final + // consonant is written; U+115F U+1160 alone draws nothing). + let opens_syllable = c == '\u{115F}' + && chars.peek().is_some_and(|&(j, n)| { + vowel_jamo(n) || (n == '\u{1160}' && name.get(j + n.len_utf8()..).and_then(|r| r.chars().next()).is_some_and(trailing_jamo)) + }); + if !pad(c) || opens_syllable { + start = i; + break; + } + } + let s = name.get(start..).unwrap_or_default(); + let mut end = s.len(); + for (i, c) in s.char_indices().rev() { + if !pad(c) { + break; + } + end = i; + } + // Take back the mark that belongs to the last character kept: one per character, so a run of + // selectors after it is still padding. + let mut prev = s.get(..end).and_then(|h| h.chars().next_back()); + for c in s.get(end..).unwrap_or_default().chars() { + let belongs = match prev { + Some(p) => attaches(c) || (c == '\u{1160}' && leading_jamo(p)), + None => false, + }; + if !belongs { + break; + } + end += c.len_utf8(); + prev = if attaches(c) { None } else { Some(c) }; + } + s.get(..end).unwrap_or_default() +} + +/// The marks among [`BLANK`] that modify the character before them: the combining grapheme joiner, +/// the Khmer inherent vowels, the Mongolian free variation selectors and the variation selectors. +fn attaches(c: char) -> bool { + matches!( + c, + '\u{34F}' | '\u{17B4}' | '\u{17B5}' | '\u{180B}'..='\u{180D}' | '\u{180F}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}' + ) +} + +/// A conjoining Hangul leading consonant (choseong), not the filler U+115F. +fn leading_jamo(c: char) -> bool { + matches!(c, '\u{1100}'..='\u{115E}' | '\u{A960}'..='\u{A97C}') +} + +/// A conjoining Hangul final consonant (jongseong). +fn trailing_jamo(c: char) -> bool { + matches!(c, '\u{11A8}'..='\u{11FF}' | '\u{D7CB}'..='\u{D7FB}') +} + +/// A conjoining Hangul vowel (jungseong) other than the vowel filler U+1160. +fn vowel_jamo(c: char) -> bool { + matches!(c, '\u{1161}'..='\u{11A7}' | '\u{D7B0}'..='\u{D7C6}') +} + /// A character that draws something on its own. fn visible(c: char) -> bool { !c.is_whitespace() && !c.is_control() && !in_ranges(c, FORMAT) && !in_ranges(c, BLANK) @@ -631,6 +716,14 @@ mod tests { "\u{3164}\u{FE0F}", " \u{3000} ", "Tone\u{7}", + "Tone\u{2028}Pro", + "Tone\u{2029}Pro", + "\u{2800}", + " \u{2800}\u{2800} ", + "\u{2065}", + "\u{FFF0}", + "\u{E0000}\u{E0002}", + "\u{E0080}\u{E0FFF}", ] { assert!(with_name(bad).is_err(), "{bad:?}"); } @@ -638,6 +731,35 @@ mod tests { for good in ["Tone…", "Kontrast ±", "می\u{200C}خواهم", "\u{1F469}\u{200D}\u{1F4BB} Code", "\u{2764}\u{FE0F} Love", "色调"] { assert_eq!(with_name(good).map(|m| m.name).ok().as_deref(), Some(good)); } + // White space and line breaks at the ends are dropped from the stored name, so the menu never + // shows them, and padding does not count towards the limit. + for (padded, stored) in [ + ("\nTone", "Tone"), + ("Tone\r\n", "Tone"), + ("\u{2028}Tone ", "Tone"), + (" Tone… ", "Tone…"), + ("Tone\u{2800}", "Tone"), + ("\u{3164}\u{2800}Tone\u{FFA0}", "Tone"), + ("\u{2764}\u{FE0F} Love\u{2800}", "\u{2764}\u{FE0F} Love"), + ("Tone\u{2065}\u{FFF0}", "Tone"), + ("\u{17B4}Tone", "Tone"), + // A selector right after the last kept character belongs to it and stays; one cut off by padding goes. + ("Love \u{2764}\u{FE0F}\u{2800}", "Love \u{2764}\u{FE0F}"), + ("Tone \u{FE0F}", "Tone"), + ("\u{FE0F}Tone", "Tone"), + ("Love \u{2764}\u{FE0F}\u{FE0F}\u{FE0F}", "Love \u{2764}\u{FE0F}"), + // Hangul filler jamo that complete a syllable are part of the name; the two fillers alone draw nothing. + ("\u{115F}\u{1160}Tone", "Tone"), + ("Tone \u{115F}\u{1160}", "Tone"), + ("Tone \u{1100}\u{1160}", "Tone \u{1100}\u{1160}"), + ("\u{115F}\u{1161} Tone", "\u{115F}\u{1161} Tone"), + ("\u{115F}\u{1160}\u{11A8} Tone", "\u{115F}\u{1160}\u{11A8} Tone"), + // Khmer inherent vowels belong to the consonant before them. + ("Tone \u{1780}\u{17B5}", "Tone \u{1780}\u{17B5}"), + ] { + assert_eq!(with_name(padded).map(|m| m.name).ok().as_deref(), Some(stored), "{padded:?}"); + } + assert_eq!(with_name(&format!("{}{}", "x".repeat(64), " ".repeat(1000))).map(|m| m.name.len()).ok(), Some(64)); // The documented limit counts characters, not bytes. assert!(with_name(&"é".repeat(64)).is_ok()); assert!(with_name(&"é".repeat(65)).is_err()); diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 88ea57c94b..c4ef6d69f0 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -18,7 +18,7 @@ photocraft-psd = { workspace = true } # No `system` feature: fontique's system backend links fontconfig on Linux. We scan font # directories ourselves (native) and always register the bundled fonts (native + web). parley = { version = "0.11", default-features = false, features = ["std"] } -skrifa = "0.44" +skrifa = "0.47" flate2 = { workspace = true } # ICU dictionary data for Japanese word boundaries and complex-script (Thai, Lao, Khmer, Burmese) diff --git a/crates/text/src/color_glyphs.rs b/crates/text/src/color_glyphs.rs new file mode 100644 index 0000000000..3426ef2e98 --- /dev/null +++ b/crates/text/src/color_glyphs.rs @@ -0,0 +1,888 @@ +//! Colour glyphs: COLR v0 layers and v1 paint graphs, coloured from the font's CPAL palette. +//! Emoji and other colour fonts draw in their own colours (#7711); the text colour fills only +//! what the font leaves to it (palette entry 0xFFFF), and its opacity applies to the whole glyph. +//! +//! skrifa walks the paint graph and calls a [`ColorPainter`]; [`Painter`] paints into a window of +//! the text raster in premultiplied sRGB, [`OutlineBounds`] only collects where it would paint. + +use photocraft_color::blend::{BlendMode, blend_rgb}; +use photocraft_doc::text::AntiAlias; +use skrifa::GlyphId; +use skrifa::color::{Brush, ColorPainter, ColorStop, CompositeMode, Extend, Transform}; +use skrifa::raw::types::BoundingBox; + +use crate::raster::{Bounds, Coverage, Xform}; +use crate::render::shape_antialias_coverage; + +/// Palette entry standing for the text colour. +const FOREGROUND: u16 = 0xFFFF; + +fn xform(t: &Transform) -> Xform { + Xform([t.xx as f64, t.yx as f64, t.xy as f64, t.yy as f64, t.dx as f64, t.dy as f64]) +} + +/// What a colour glyph clips to: a glyph outline or a COLR clip box, both in font units through +/// the paint transform. The caller draws either one the same way (bent with the type, for +/// warped text), so a clip box follows the glyph it crops. +#[derive(Clone, Copy)] +pub(crate) enum Shape { + Glyph(GlyphId), + Box(BoundingBox), +} + +/// A painter that ignores everything, to check that a colour glyph's paint graph can be walked +/// before the glyph is drawn in colour ([`crate::render`] draws its outline otherwise). +pub(crate) struct NoPaint; + +impl ColorPainter for NoPaint { + fn push_transform(&mut self, _: Transform) {} + fn pop_transform(&mut self) {} + fn push_clip_glyph(&mut self, _: GlyphId) {} + fn push_clip_box(&mut self, _: BoundingBox) {} + fn pop_clip(&mut self) {} + fn fill(&mut self, _: Brush<'_>) {} + fn push_layer(&mut self, _: CompositeMode) {} +} + +/// Collects where a colour glyph paints, for the ink bounds: every fill adds the intersection of +/// the clips around it, so a large clip box around small artwork does not widen the bounds. +/// `outline` draws a [`Shape`] (through the given paint transform) into a [`Bounds`] in sink +/// space. A fill outside every clip is unbounded and adds nothing. +pub(crate) struct OutlineBounds<'a, F: FnMut(Shape, &Xform, &mut Bounds)> { + pub sink: &'a mut Bounds, + pub outline: F, + xforms: Vec, + /// The intersection of the clips so far; `None` when it is empty. + clips: Vec>, +} + +impl<'a, F: FnMut(Shape, &Xform, &mut Bounds)> OutlineBounds<'a, F> { + pub fn new(sink: &'a mut Bounds, outline: F) -> Self { + Self { sink, outline, xforms: Vec::new(), clips: Vec::new() } + } + fn current(&self) -> Xform { + self.xforms.last().copied().unwrap_or(Xform::IDENTITY) + } + fn push(&mut self, shape: Shape) { + let mut b = Bounds::default(); + let m = self.current(); + (self.outline)(shape, &m, &mut b); + let r = match (self.clips.last(), b.rect) { + (_, None) => None, + (None, r) => r, + (Some(None), _) => None, + (Some(Some(o)), Some(r)) => { + let i = [o[0].max(r[0]), o[1].max(r[1]), o[2].min(r[2]), o[3].min(r[3])]; + (i[0] <= i[2] && i[1] <= i[3]).then_some(i) + } + }; + self.clips.push(r); + } +} + +impl ColorPainter for OutlineBounds<'_, F> { + fn push_transform(&mut self, t: Transform) { + self.xforms.push(self.current().mul(&xform(&t))); + } + fn pop_transform(&mut self) { + self.xforms.pop(); + } + fn push_clip_glyph(&mut self, id: GlyphId) { + self.push(Shape::Glyph(id)); + } + fn push_clip_box(&mut self, b: BoundingBox) { + self.push(Shape::Box(b)); + } + fn pop_clip(&mut self) { + self.clips.pop(); + } + fn fill(&mut self, _: Brush<'_>) { + if let Some(Some([x0, y0, x1, y1])) = self.clips.last().copied() { + self.sink.add((x0, y0)); + self.sink.add((x1, y1)); + } + } + fn push_layer(&mut self, _: CompositeMode) {} +} + +/// A gradient's colour line: premultiplied stops in offset order. +struct ColorLine { + stops: Vec<(f32, [f32; 4])>, + extend: Extend, +} + +impl ColorLine { + fn at(&self, t: f32) -> [f32; 4] { + let (Some(first), Some(last)) = (self.stops.first(), self.stops.last()) else { return [0.0; 4] }; + // Repeat and Reflect run over the stops' own span, which COLR doesn't pin to 0..1; Pad is + // the first/last stop beyond it. + let (t0, span) = (first.0, last.0 - first.0); + let t = match self.extend { + Extend::Repeat if span > 0.0 => t0 + (t - t0).rem_euclid(span), + Extend::Reflect if span > 0.0 => { + let m = (t - t0).rem_euclid(2.0 * span); + t0 + if m > span { 2.0 * span - m } else { m } + } + _ => t, + }; + if t.is_nan() || t < first.0 { + return first.1; + } + if t >= last.0 { + return last.1; + } + // The last stop at or before `t`: where several stops share an offset, the last of them + // holds from that offset on (OpenType COLR, colour lines), so a pixel landing exactly on + // a hard transition takes the colour after it. The next stop then lies strictly after. + let i = self.stops.partition_point(|s| s.0 <= t); + let (Some(&(o0, c0)), Some(&(o1, c1))) = (i.checked_sub(1).and_then(|i| self.stops.get(i)), self.stops.get(i)) else { return last.1 }; + let k = if o1 > o0 { (t - o0) / (o1 - o0) } else { 1.0 }; + std::array::from_fn(|i| c0[i] + (c1[i] - c0[i]) * k) + } +} + +/// What a fill paints, resolved to premultiplied colours. +enum Paint { + Solid([f32; 4]), + Linear { p0: (f32, f32), d: (f32, f32), len2: f32, line: ColorLine }, + Radial { c0: (f32, f32), r0: f32, cd: (f32, f32), dr: f32, line: ColorLine }, + Sweep { c: (f32, f32), start: f32, end: f32, line: ColorLine }, +} + +impl Paint { + /// The colour at a point in paint space (font units); `None` where a radial gradient is + /// undefined (the point lies outside every circle of the cone). + fn at(&self, u: f32, v: f32) -> Option<[f32; 4]> { + match self { + Paint::Solid(c) => Some(*c), + Paint::Linear { p0, d, len2, line } => Some(line.at(((u - p0.0) * d.0 + (v - p0.1) * d.1) / len2)), + Paint::Radial { c0, r0, cd, dr, line } => { + // The largest t with |p - c(t)| = r(t) and r(t) >= 0 (two-point conical gradient). + let (px, py) = (u - c0.0, v - c0.1); + let a = cd.0 * cd.0 + cd.1 * cd.1 - dr * dr; + let b = px * cd.0 + py * cd.1 + r0 * dr; + let c = px * px + py * py - r0 * r0; + let ok = |t: f32| t.is_finite() && r0 + t * dr >= 0.0; + if a.abs() < 1e-6 { + if b == 0.0 && c == 0.0 { + // Every circle passes through p (the shared point of touching circles), + // so the largest t wins: where shrinking circles reach radius 0, or the + // end of the colour line when they grow. Equal circles paint nothing. + return match dr.partial_cmp(&0.0) { + Some(std::cmp::Ordering::Less) => Some(line.at(-r0 / dr)), + Some(std::cmp::Ordering::Greater) => line.stops.last().map(|s| s.1), + _ => None, + }; + } + let t = c / (2.0 * b); + return ok(t).then(|| line.at(t)); + } + let disc = b * b - a * c; + if disc < 0.0 { + return None; + } + let s = disc.sqrt(); + let (t1, t2) = ((b + s) / a, (b - s) / a); + let (hi, lo) = if t1 >= t2 { (t1, t2) } else { (t2, t1) }; + [hi, lo].into_iter().find(|t| ok(*t)).map(|t| line.at(t)) + } + Paint::Sweep { c, start, end, line } => { + // skrifa hands the angles clockwise (360° minus the font's counter-clockwise ones). + let ccw = (v - c.1).atan2(u - c.0).to_degrees(); + // skrifa's start and end may lie outside 0..360 (a sweep from 270° to 450° + // crosses the positive x axis): take the turn of the angle that falls inside them. + let mut cw = (360.0 - ccw).rem_euclid(360.0); + let turn = cw + 360.0 * ((start - cw) / 360.0).ceil(); + if turn.is_finite() && turn <= *end { + cw = turn; + } + let span = end - start; + let t = if span.abs() > 1e-6 { + (cw - start) / span + } else if cw >= *start { + 1.0 + } else { + 0.0 + }; + Some(line.at(t)) + } + } + } +} + +/// Premultiplied Porter-Duff or blend-mode composite of `s` over `b`. +fn composite(mode: CompositeMode, b: [f32; 4], s: [f32; 4]) -> [f32; 4] { + let (ab, as_) = (b[3], s[3]); + let blend = match mode { + CompositeMode::Screen => Some(BlendMode::Screen), + CompositeMode::Overlay => Some(BlendMode::Overlay), + CompositeMode::Darken => Some(BlendMode::Darken), + CompositeMode::Lighten => Some(BlendMode::Lighten), + CompositeMode::ColorDodge => Some(BlendMode::ColorDodge), + CompositeMode::ColorBurn => Some(BlendMode::ColorBurn), + CompositeMode::HardLight => Some(BlendMode::HardLight), + CompositeMode::SoftLight => Some(BlendMode::SoftLight), + CompositeMode::Difference => Some(BlendMode::Difference), + CompositeMode::Exclusion => Some(BlendMode::Exclusion), + CompositeMode::Multiply => Some(BlendMode::Multiply), + CompositeMode::HslHue => Some(BlendMode::Hue), + CompositeMode::HslSaturation => Some(BlendMode::Saturation), + CompositeMode::HslColor => Some(BlendMode::Color), + CompositeMode::HslLuminosity => Some(BlendMode::Luminosity), + _ => None, + }; + if let Some(m) = blend { + if ab <= 0.0 || as_ <= 0.0 { + return std::array::from_fn(|i| s[i] + b[i] * (1.0 - as_)); + } + let mixed = blend_rgb(m, [b[0] / ab, b[1] / ab, b[2] / ab], [s[0] / as_, s[1] / as_, s[2] / as_]); + let mut out = [0.0; 4]; + for i in 0..3 { + out[i] = s[i] * (1.0 - ab) + b[i] * (1.0 - as_) + as_ * ab * mixed[i]; + } + out[3] = as_ + ab - as_ * ab; + return out; + } + let (fs, fb) = match mode { + CompositeMode::Clear => (0.0, 0.0), + CompositeMode::Src => (1.0, 0.0), + CompositeMode::Dest => (0.0, 1.0), + CompositeMode::DestOver => (1.0 - ab, 1.0), + CompositeMode::SrcIn => (ab, 0.0), + CompositeMode::DestIn => (0.0, as_), + CompositeMode::SrcOut => (1.0 - ab, 0.0), + CompositeMode::DestOut => (0.0, 1.0 - as_), + CompositeMode::SrcAtop => (ab, 1.0 - as_), + CompositeMode::DestAtop => (1.0 - ab, as_), + CompositeMode::Xor => (1.0 - ab, 1.0 - as_), + CompositeMode::Plus => (1.0, 1.0), + _ => (1.0, 1.0 - as_), + }; + std::array::from_fn(|i| (s[i] * fs + b[i] * fb).min(1.0)) +} + +/// What one render may still spend on colour glyphs, shared by all of them: `bytes` of buffers +/// live at once (the window layers and clip masks), and `work`, pixels touched by fills, clips +/// and composites, against the same cumulative budget as the plain colour passes. A glyph that +/// would overrun either one fails, and the text renders nothing, as with the other budgets. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Limits { + pub bytes: u64, + pub work: u64, +} + +/// The colours a glyph paints with. +pub(crate) struct Ink<'a> { + pub palette: &'a [skrifa::color::Color], + /// The text colour, straight sRGB and alpha. + pub foreground: [f32; 4], +} + +/// A window-sized layer and how many clips were already pushed when it was opened: clips from +/// outside a layer do not shape what is painted into it, they apply once when it is merged down. +struct Layer { + px: Vec<[f32; 4]>, + clip_base: usize, +} + +/// Paints one colour glyph into a `w × h` window, premultiplied sRGB. `outline` adds a +/// [`Shape`]'s coverage (through the given paint transform) to a window-sized [`Coverage`]; +/// `to_window` maps font units into the window (gradients). +pub(crate) struct Painter<'a, F: FnMut(Shape, &Xform, &mut Coverage)> { + w: usize, + h: usize, + outline: F, + to_window: Xform, + ink: Ink<'a>, + antialias: AntiAlias, + limits: Limits, + xforms: Vec, + clips: Vec>, + layers: Vec, + /// A buffer could not be reserved or a budget ran out: [`Painter::finish`] returns `None`. + /// Placeholders (empty buffers) keep pushes and pops balanced and paint nothing. + failed: bool, +} + +/// `len` copies of `v`, or `None` when its bytes cannot be reserved. +fn filled(len: usize, v: T) -> Option> { + let mut out = Vec::new(); + out.try_reserve_exact(len).ok()?; + out.resize(len, v); + Some(out) +} + +impl<'a, F: FnMut(Shape, &Xform, &mut Coverage)> Painter<'a, F> { + pub fn new(w: usize, h: usize, outline: F, to_window: Xform, ink: Ink<'a>, antialias: AntiAlias, limits: Limits) -> Self { + let mut p = Self { w, h, outline, to_window, ink, antialias, limits, xforms: Vec::new(), clips: Vec::new(), layers: Vec::new(), failed: false }; + let base = p.new_layer().unwrap_or_default(); + p.layers.push(Layer { px: base, clip_base: 0 }); + p + } + + /// The pixel work left after this glyph; its buffers' bytes come back once it is done. + pub fn work_left(&self) -> u64 { + self.limits.work + } + + /// The painted glyph, premultiplied sRGB, row-major, or `None` when a buffer could not be + /// reserved or a budget ran out. + pub fn finish(mut self) -> Option> { + if self.failed { + return None; + } + self.layers.truncate(1); + self.layers.pop().map(|l| l.px) + } + + fn pixels(&self) -> Option { + (self.w as u64).checked_mul(self.h as u64) + } + + /// Takes `bytes` of buffers and, with `work`, one window's worth of pixel work from the + /// budgets; `false` (and the painter failed) when they don't fit or it failed already. + fn spend(&mut self, bytes: Option, work: bool) -> bool { + let work = if work { self.pixels() } else { Some(0) }; + match (bytes.and_then(|b| self.limits.bytes.checked_sub(b)), work.and_then(|n| self.limits.work.checked_sub(n))) { + (Some(b), Some(w)) if !self.failed => { + self.limits = Limits { bytes: b, work: w }; + true + } + _ => { + self.failed = true; + false + } + } + } + + /// Returns the bytes of `len` elements of `each` bytes to the budget. + fn give_back(&mut self, len: usize, each: usize) { + let b = (len as u64).saturating_mul(each as u64); + self.limits.bytes = self.limits.bytes.saturating_add(b); + } + + /// A transparent window-sized layer, its bytes taken from the budget. + fn new_layer(&mut self) -> Option> { + let bytes = self.pixels().and_then(|n| n.checked_mul(size_of::<[f32; 4]>() as u64)); + if !self.spend(bytes, false) { + return None; + } + let v = self.w.checked_mul(self.h).and_then(|n| filled(n, [0.0; 4])); + self.failed |= v.is_none(); + v + } + + fn current(&self) -> Xform { + self.xforms.last().copied().unwrap_or(Xform::IDENTITY) + } + + /// The innermost clip pushed inside the current layer, if any. + fn layer_clip(&self) -> Option<&Vec> { + let base = self.layers.last().map_or(0, |l| l.clip_base); + if self.clips.len() > base { self.clips.last() } else { None } + } + + /// Rasterises `shape` into a clip mask, intersected with the clip around it in this layer: + /// the smaller coverage per pixel, so a glyph clipped by its own outline again (or by a box + /// around it) keeps its anti-aliased edge instead of squaring it. + fn push_shape(&mut self, shape: Shape) { + // A mask is kept at one f32 per pixel; while it is built, the coverage accumulator and + // the finished vector are live side by side. + let mask = self.pixels().and_then(|n| n.checked_mul(size_of::() as u64)); + let cov = if self.spend(mask.and_then(|m| m.checked_mul(2)), true) { Coverage::try_new(self.w, self.h) } else { None }; + let Some(mut cov) = cov else { + self.failed = true; + self.clips.push(Vec::new()); + return; + }; + let m = self.current(); + (self.outline)(shape, &m, &mut cov); + let c = cov.finish(); + // The accumulator is gone again: its half of the reservation comes back. + self.give_back(self.w.saturating_mul(self.h), size_of::()); + let Some(mut c) = c else { + self.failed = true; + self.clips.push(Vec::new()); + return; + }; + let mode = self.antialias; + c.iter_mut().for_each(|v| *v = shape_antialias_coverage(*v, mode)); + if let Some(outer) = self.layer_clip() { + c.iter_mut().zip(outer).for_each(|(v, o)| *v = v.min(*o)); + } + self.clips.push(c); + } + + /// A palette entry (or the text colour), premultiplied, times `alpha`. + fn color(&self, index: u16, alpha: f32) -> [f32; 4] { + let [r, g, b, a] = if index == FOREGROUND { + self.ink.foreground + } else { + match self.ink.palette.get(usize::from(index)) { + Some(c) => [c.red, c.green, c.blue, c.alpha].map(|v| f32::from(v) / 255.0), + None => return [0.0; 4], + } + }; + let a = (a * alpha).clamp(0.0, 1.0); + [r * a, g * a, b * a, a] + } + + fn line(&self, stops: &[ColorStop], extend: Extend) -> ColorLine { + let mut stops: Vec<(f32, [f32; 4])> = stops.iter().filter(|s| s.offset.is_finite()).map(|s| (s.offset, self.color(s.palette_index, s.alpha))).collect(); + stops.sort_by(|a, b| a.0.total_cmp(&b.0)); + ColorLine { stops, extend } + } + + fn paint(&self, brush: Brush<'_>) -> Option { + let pt = |p: skrifa::raw::types::Point| (p.x, p.y); + Some(match brush { + Brush::Solid { palette_index, alpha } => Paint::Solid(self.color(palette_index, alpha)), + Brush::LinearGradient { p0, p1, color_stops, extend } => { + let d = (p1.x - p0.x, p1.y - p0.y); + let len2 = d.0 * d.0 + d.1 * d.1; + if !len2.is_normal() || color_stops.is_empty() { + return None; + } + Paint::Linear { p0: pt(p0), d, len2, line: self.line(color_stops, extend) } + } + Brush::RadialGradient { c0, r0, c1, r1, color_stops, extend } => { + if color_stops.is_empty() { + return None; + } + Paint::Radial { c0: pt(c0), r0, cd: (c1.x - c0.x, c1.y - c0.y), dr: r1 - r0, line: self.line(color_stops, extend) } + } + Brush::SweepGradient { c0, start_angle, end_angle, color_stops, extend } => { + if color_stops.is_empty() { + return None; + } + Paint::Sweep { c: pt(c0), start: start_angle, end: end_angle, line: self.line(color_stops, extend) } + } + }) + } +} + +impl ColorPainter for Painter<'_, F> { + fn push_transform(&mut self, t: Transform) { + self.xforms.push(self.current().mul(&xform(&t))); + } + fn pop_transform(&mut self) { + self.xforms.pop(); + } + fn push_clip_glyph(&mut self, id: GlyphId) { + self.push_shape(Shape::Glyph(id)); + } + fn push_clip_box(&mut self, b: BoundingBox) { + self.push_shape(Shape::Box(b)); + } + fn pop_clip(&mut self) { + if let Some(c) = self.clips.pop() { + self.give_back(c.len(), size_of::()); + } + } + fn fill(&mut self, brush: Brush<'_>) { + if !self.spend(Some(0), true) { + return; + } + let Some(paint) = self.paint(brush) else { return }; + let to_paint = self.to_window.mul(&self.current()).invert(); + let w = self.w; + let base = self.layers.last().map_or(0, |l| l.clip_base); + let clip = if self.clips.len() > base { self.clips.last() } else { None }; + let Some(layer) = self.layers.last_mut() else { return }; + for (i, px) in layer.px.iter_mut().enumerate() { + let k = clip.map_or(1.0, |c| c.get(i).copied().unwrap_or(0.0)); + if k <= 0.0 { + continue; + } + let src = match (&paint, &to_paint) { + (Paint::Solid(c), _) => Some(*c), + (_, Some(inv)) => { + let (u, v) = inv.apply((i % w) as f64 + 0.5, (i / w) as f64 + 0.5); + paint.at(u as f32, v as f32) + } + (_, None) => None, + }; + let Some(s) = src else { continue }; + let keep = 1.0 - s[3] * k; + for j in 0..4 { + px[j] = s[j] * k + px[j] * keep; + } + } + } + fn push_layer(&mut self, _: CompositeMode) { + // No fixed depth: skrifa stops at 64 nested paints, and the byte budget bounds the rest. + let px = self.new_layer().unwrap_or_default(); + self.layers.push(Layer { px, clip_base: self.clips.len() }); + } + fn pop_layer_with_mode(&mut self, mode: CompositeMode) { + if self.layers.len() < 2 { + return; + } + let Some(src) = self.layers.pop() else { return }; + self.give_back(src.px.len(), size_of::<[f32; 4]>()); + if !self.spend(Some(0), true) { + return; + } + // The clips around the merged layer (inside the one below) apply once, to the result. + let base = self.layers.last().map_or(0, |l| l.clip_base); + let clip = if self.clips.len() > base { self.clips.last() } else { None }; + let Some(dst) = self.layers.last_mut() else { return }; + for (i, (b, s)) in dst.px.iter_mut().zip(&src.px).enumerate() { + let k = clip.map_or(1.0, |c| c.get(i).copied().unwrap_or(0.0)); + if k <= 0.0 { + continue; + } + let c = composite(mode, *b, *s); + *b = std::array::from_fn(|j| b[j] + (c[j] - b[j]) * k); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::raster::rect_to; + + const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; + const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; + + fn line(extend: Extend) -> ColorLine { + ColorLine { stops: vec![(0.0, RED), (1.0, BLUE)], extend } + } + + #[test] + fn colour_line_extends_pad_repeat_and_reflect() { + let mid = |c: [f32; 4]| (c[0] - 0.5).abs() < 1e-6 && (c[2] - 0.5).abs() < 1e-6; + assert!(mid(line(Extend::Pad).at(0.5))); + assert_eq!(line(Extend::Pad).at(-3.0), RED); + assert_eq!(line(Extend::Pad).at(7.0), BLUE); + assert_eq!(line(Extend::Pad).at(f32::NAN), RED); + assert!(mid(line(Extend::Repeat).at(1.5))); + assert!((line(Extend::Repeat).at(1.25)[0] - 0.75).abs() < 1e-6); + assert!((line(Extend::Reflect).at(1.25)[0] - 0.25).abs() < 1e-6); + assert_eq!(ColorLine { stops: Vec::new(), extend: Extend::Pad }.at(0.5), [0.0; 4]); + } + + #[test] + fn colour_line_extends_over_its_stops_not_over_0_to_1() { + // COLR repeats and reflects over [first stop, last stop], and stops may lie outside 0..1. + let inner = |extend| ColorLine { stops: vec![(0.25, RED), (0.75, BLUE)], extend }; + let red_share = |c: [f32; 4]| c[0]; + // Period 0.5: 0.875 repeats 0.375 (a quarter of the way to blue). + assert!((red_share(inner(Extend::Repeat).at(0.875)) - 0.75).abs() < 1e-5); + // Reflect: 0.875 mirrors 0.625 (three quarters of the way to blue). + assert!((red_share(inner(Extend::Reflect).at(0.875)) - 0.25).abs() < 1e-5); + // Pad reaches stops outside 0..1. + let wide = ColorLine { stops: vec![(-0.5, RED), (1.5, BLUE)], extend: Extend::Pad }; + assert!((red_share(wide.at(0.0)) - 0.75).abs() < 1e-5); + assert_eq!(wide.at(1.5), BLUE); + } + + const RED_PAL: [skrifa::color::Color; 2] = + [skrifa::color::Color { red: 255, green: 0, blue: 0, alpha: 255 }, skrifa::color::Color { red: 0, green: 0, blue: 255, alpha: 255 }]; + const PLENTY: Limits = Limits { bytes: u64::MAX, work: u64::MAX }; + + fn ink() -> Ink<'static> { + Ink { palette: &RED_PAL, foreground: [0.0, 0.0, 0.0, 1.0] } + } + + /// Draws every shape as given, glyph `n` as the rectangle 0..n x 0..8 (window pixels). + fn shapes(shape: Shape, m: &Xform, c: &mut Coverage) { + match shape { + Shape::Glyph(id) => rect_to(c, m, 0.0, 0.0, f64::from(id.to_u32()) * 0.5, 8.0), + Shape::Box(b) => rect_to(c, m, f64::from(b.x_min), f64::from(b.y_min), f64::from(b.x_max), f64::from(b.y_max)), + } + } + + fn solid(index: u16) -> Brush<'static> { + Brush::Solid { palette_index: index, alpha: 1.0 } + } + + #[test] + fn clip_boxes_are_drawn_the_way_the_glyphs_are() { + // Clip boxes go through the same drawing as the clip glyphs, so bent type bends its clip + // boxes too instead of dropping them. A stand-in "bend" here shifts everything 4 px right. + let bent = |shape: Shape, m: &Xform, c: &mut Coverage| shapes(shape, &Xform([1.0, 0.0, 0.0, 1.0, 4.0, 0.0]).mul(m), c); + let mut p = Painter::new(8, 8, bent, Xform::IDENTITY, ink(), AntiAlias::Smooth, PLENTY); + p.push_clip_box(BoundingBox { x_min: 0.0, y_min: 0.0, x_max: 2.0, y_max: 2.0 }); + p.push_clip_glyph(GlyphId::new(16)); + p.fill(solid(0)); + p.pop_clip(); + p.pop_clip(); + let px = p.finish().unwrap_or_default(); + // The box moved with the shapes: 4..6 is painted, 0..2 and the rest are not. + assert_eq!(px.get(8 + 5).map(|c| c[3]), Some(1.0)); + assert_eq!(px.get(8 + 1).map(|c| c[3]), Some(0.0)); + assert_eq!(px.get(5 * 8 + 5).map(|c| c[3]), Some(0.0)); + } + + #[test] + fn a_window_too_large_to_reserve_paints_nothing() { + // Coverage buffers are fallible on main (#4979); a colour glyph whose window cannot be + // reserved gives `None` instead of aborting, and its clips stay balanced. + let mut p = Painter::new(usize::MAX / 2, 4, shapes, Xform::IDENTITY, ink(), AntiAlias::Smooth, PLENTY); + p.push_clip_box(BoundingBox { x_min: 0.0, y_min: 0.0, x_max: 2.0, y_max: 2.0 }); + p.push_clip_glyph(GlyphId::new(1)); + p.push_layer(CompositeMode::SrcOver); + p.fill(solid(0)); + p.pop_layer_with_mode(CompositeMode::SrcOver); + p.pop_clip(); + p.pop_clip(); + assert!(p.finish().is_none()); + } + + #[test] + fn layers_and_clips_count_against_the_byte_budget() { + // An 8x8 window: 1 KiB per layer, 256 bytes per clip mask (512 while it is built). + let run = |bytes: u64| { + let mut p = Painter::new(8, 8, shapes, Xform::IDENTITY, ink(), AntiAlias::Smooth, Limits { bytes, work: u64::MAX }); + p.push_clip_glyph(GlyphId::new(16)); + for _ in 0..3 { + p.push_layer(CompositeMode::SrcOver); + } + p.fill(solid(0)); + for _ in 0..3 { + p.pop_layer_with_mode(CompositeMode::SrcOver); + } + p.pop_clip(); + p.finish() + }; + // Base layer, mask and three layers live at once. + assert!(run(4 * 1024 + 512).is_some()); + assert!(run(4 * 1024 + 255).is_none()); + // Buffers come back when popped: one more layer later on fits in the same budget. + let mut p = Painter::new(8, 8, shapes, Xform::IDENTITY, ink(), AntiAlias::Smooth, Limits { bytes: 2 * 1024, work: u64::MAX }); + for _ in 0..5 { + p.push_layer(CompositeMode::SrcOver); + p.fill(solid(0)); + p.pop_layer_with_mode(CompositeMode::SrcOver); + } + assert!(p.finish().is_some()); + } + + #[test] + fn colour_glyph_work_is_capped() { + // Each fill, clip and merge touches the whole 8x8 window (64 px of work). + let run = |work: u64| { + let mut p = Painter::new(8, 8, shapes, Xform::IDENTITY, ink(), AntiAlias::Smooth, Limits { bytes: u64::MAX, work }); + for _ in 0..3 { + p.fill(solid(0)); + } + let left = p.work_left(); + (p.finish().is_some(), left) + }; + assert_eq!(run(3 * 64), (true, 0)); + assert!(!run(3 * 64 - 1).0); + } + + #[test] + fn deep_composites_keep_their_modes() { + // Past what used to be an eight-layer cap, a nested Clear still clears: the red fill + // underneath must not show. + let mut p = Painter::new(4, 4, shapes, Xform::IDENTITY, ink(), AntiAlias::Smooth, PLENTY); + for _ in 0..9 { + p.push_layer(CompositeMode::SrcOver); + } + p.fill(solid(0)); + p.push_layer(CompositeMode::Clear); + p.fill(solid(1)); + p.pop_layer_with_mode(CompositeMode::Clear); + for _ in 0..9 { + p.pop_layer_with_mode(CompositeMode::SrcOver); + } + let px = p.finish().unwrap_or_default(); + assert_eq!(px.len(), 16); + assert!(px.iter().all(|c| c[3] == 0.0), "{:?}", px.first()); + } + + #[test] + fn a_glyph_clip_applies_once_to_a_composite_inside_it() { + // A PaintGlyph around a SrcIn composite: the edge pixel half covered by the glyph ends + // up half opaque, not a quarter (the clip on both the backdrop and the source). + let mut p = Painter::new( + 2, + 1, + |s: Shape, m: &Xform, c: &mut Coverage| { + if let Shape::Glyph(_) = s { + rect_to(c, m, 0.0, 0.0, 1.5, 1.0); + } + }, + Xform::IDENTITY, + ink(), + AntiAlias::Smooth, + PLENTY, + ); + p.push_clip_glyph(GlyphId::new(1)); + p.push_layer(CompositeMode::SrcOver); + p.fill(solid(0)); + p.push_layer(CompositeMode::SrcIn); + p.fill(solid(1)); + p.pop_layer_with_mode(CompositeMode::SrcIn); + p.pop_layer_with_mode(CompositeMode::SrcOver); + p.pop_clip(); + let px = p.finish().unwrap_or_default(); + assert_eq!(px.first().map(|c| c[3]), Some(1.0)); + let edge = px.get(1).copied().unwrap_or_default(); + assert!((edge[3] - 0.5).abs() < 1e-5 && (edge[2] - 0.5).abs() < 1e-5, "{edge:?}"); + } + + #[test] + fn a_composite_leaves_pixels_outside_its_clip_alone() { + // Red everywhere, then a Src composite of blue inside a clip over the left pixel only: + // Src replaces what is below, but only where the clip lets it. + let mut p = Painter::new( + 2, + 1, + |s: Shape, m: &Xform, c: &mut Coverage| { + if let Shape::Glyph(_) = s { + rect_to(c, m, 0.0, 0.0, 1.0, 1.0); + } + }, + Xform::IDENTITY, + ink(), + AntiAlias::Smooth, + PLENTY, + ); + p.fill(solid(0)); + p.push_clip_glyph(GlyphId::new(1)); + p.push_layer(CompositeMode::Src); + p.fill(solid(1)); + p.pop_layer_with_mode(CompositeMode::Src); + p.pop_clip(); + let px = p.finish().unwrap_or_default(); + assert_eq!(px, vec![BLUE, RED]); + } + + #[test] + fn colour_glyph_edges_follow_the_anti_alias_mode() { + // A clip covering 0.5 of a pixel: Smooth keeps 0.5, Sharp thins it as the plain passes do. + let paint = |mode| { + let mut p = Painter::new(1, 1, |_: Shape, m: &Xform, c: &mut Coverage| rect_to(c, m, 0.0, 0.0, 0.5, 1.0), Xform::IDENTITY, ink(), mode, PLENTY); + p.push_clip_glyph(GlyphId::new(1)); + p.fill(solid(0)); + p.pop_clip(); + p.finish().unwrap_or_default().first().map_or(0.0, |c| c[3]) + }; + assert!((paint(AntiAlias::Smooth) - 0.5).abs() < 1e-5); + assert!((paint(AntiAlias::Sharp) - shape_antialias_coverage(0.5, AntiAlias::Sharp)).abs() < 1e-5); + assert!(paint(AntiAlias::Sharp) < 0.3); + assert_eq!(paint(AntiAlias::None), 1.0); + } + + #[test] + fn ink_bounds_take_the_intersection_of_the_clips() { + // A small glyph inside a huge clip box: the bounds are the glyph's, not the box's. + let mut b = Bounds::default(); + let to = |s: Shape, m: &Xform, b: &mut Bounds| match s { + Shape::Glyph(_) => rect_to(b, m, 0.0, 0.0, 8.0, 8.0), + Shape::Box(r) => rect_to(b, m, f64::from(r.x_min), f64::from(r.y_min), f64::from(r.x_max), f64::from(r.y_max)), + }; + let mut o = OutlineBounds::new(&mut b, to); + o.push_clip_box(BoundingBox { x_min: -1e6, y_min: -1e6, x_max: 1e6, y_max: 1e6 }); + o.push_clip_glyph(GlyphId::new(1)); + o.fill(solid(0)); + o.pop_clip(); + // Clips that don't overlap paint nothing. + o.push_clip_box(BoundingBox { x_min: 100.0, y_min: 100.0, x_max: 200.0, y_max: 200.0 }); + o.push_clip_glyph(GlyphId::new(1)); + o.fill(solid(0)); + o.pop_clip(); + o.pop_clip(); + o.pop_clip(); + assert_eq!(b.rect, Some([0.0, 0.0, 8.0, 8.0])); + } + + #[test] + fn coincident_stops_switch_at_their_offset() { + // A hard red-to-blue step at 0.5: exactly at 0.5 the colour after the step holds. + let step = ColorLine { stops: vec![(0.0, RED), (0.5, RED), (0.5, BLUE), (1.0, BLUE)], extend: Extend::Pad }; + assert_eq!(step.at(0.5), BLUE); + assert_eq!(step.at(0.499), RED); + assert_eq!(step.at(0.0), RED); + // Several stops at the very start: the last of them holds from there. + let start = ColorLine { stops: vec![(0.0, RED), (0.0, BLUE), (1.0, BLUE)], extend: Extend::Pad }; + assert_eq!(start.at(0.0), BLUE); + assert_eq!(start.at(-1.0), RED); + } + + #[test] + fn sweep_angles_past_360_reach_the_positive_x_axis() { + // skrifa's 270°..450° (clockwise) crosses the positive x axis at 360°, the midpoint. + let p = Paint::Sweep { c: (0.0, 0.0), start: 270.0, end: 450.0, line: line(Extend::Pad) }; + let mid = p.at(1.0, 0.0).unwrap_or_default(); + assert!((mid[0] - 0.5).abs() < 1e-4 && (mid[2] - 0.5).abs() < 1e-4, "{mid:?}"); + // A sweep starting below 0°: 350° is -10°, a sixth of the way through -30°..30°. + let p = Paint::Sweep { c: (0.0, 0.0), start: -30.0, end: 30.0, line: line(Extend::Pad) }; + let ccw10 = 10f32.to_radians(); + let c = p.at(ccw10.cos(), ccw10.sin()).unwrap_or_default(); + assert!((c[2] - 1.0 / 3.0).abs() < 1e-3, "{c:?}"); + } + + #[test] + fn radial_gradient_is_the_two_point_cone() { + // Concentric circles, radius 0 to 10: t is the distance over 10, red at the centre. + let p = Paint::Radial { c0: (0.0, 0.0), r0: 0.0, cd: (0.0, 0.0), dr: 10.0, line: line(Extend::Pad) }; + assert_eq!(p.at(0.0, 0.0), Some(RED)); + let c = p.at(3.0, 4.0).unwrap_or_default(); + assert!((c[0] - 0.5).abs() < 1e-5, "{c:?}"); + assert_eq!(p.at(30.0, 0.0), Some(BLUE)); + // Two equal circles side by side: no cone covers a point far above them. + let p = Paint::Radial { c0: (0.0, 0.0), r0: 1.0, cd: (4.0, 0.0), dr: 0.0, line: line(Extend::Pad) }; + assert_eq!(p.at(2.0, 50.0), None); + assert!(p.at(2.0, 0.5).is_some()); + } + + #[test] + fn touching_circles_paint_their_shared_point() { + // Circles grow from radius 0 at the origin to the right, all through the origin: there + // the largest t is unbounded, the end of the colour line (it used to divide 0 by 0). + let p = Paint::Radial { c0: (0.0, 0.0), r0: 0.0, cd: (1.0, 0.0), dr: 1.0, line: line(Extend::Pad) }; + assert_eq!(p.at(0.0, 0.0), Some(BLUE)); + assert!(p.at(1.0, 0.0).is_some()); + // Shrinking circles, all through (2, 0): the largest t is where the radius reaches 0. + let p = Paint::Radial { c0: (0.0, 0.0), r0: 2.0, cd: (2.0, 0.0), dr: -2.0, line: line(Extend::Pad) }; + assert_eq!(p.at(2.0, 0.0), Some(BLUE)); + // Equal circles in the same place: no cone, nothing painted, not even on the circle. + let p = Paint::Radial { c0: (0.0, 0.0), r0: 1.0, cd: (0.0, 0.0), dr: 0.0, line: line(Extend::Pad) }; + assert_eq!(p.at(1.0, 0.0), None); + } + + #[test] + fn a_glyph_clipped_by_its_own_outline_keeps_its_edge() { + // The same half-covered outline twice: the edge stays half opaque, not a quarter. + let mut p = + Painter::new(1, 1, |_: Shape, m: &Xform, c: &mut Coverage| rect_to(c, m, 0.0, 0.0, 0.5, 1.0), Xform::IDENTITY, ink(), AntiAlias::Smooth, PLENTY); + p.push_clip_glyph(GlyphId::new(1)); + p.push_clip_glyph(GlyphId::new(1)); + p.fill(solid(0)); + p.pop_clip(); + p.pop_clip(); + let a = p.finish().unwrap_or_default().first().map_or(0.0, |c| c[3]); + assert!((a - 0.5).abs() < 1e-5, "{a}"); + } + + #[test] + fn sweep_gradient_turns_clockwise_from_the_start_angle() { + // skrifa's angles: clockwise, i.e. 360° minus the font's counter-clockwise ones. + let p = Paint::Sweep { c: (0.0, 0.0), start: 0.0, end: 360.0, line: line(Extend::Pad) }; + // Font space is y up: (0, -1) is 90° counter-clockwise below, 90° clockwise. + let below = p.at(0.0, -1.0).unwrap_or_default(); + assert!((below[2] - 0.25).abs() < 1e-4, "{below:?}"); + let above = p.at(0.0, 1.0).unwrap_or_default(); + assert!((above[2] - 0.75).abs() < 1e-4, "{above:?}"); + } + + #[test] + fn layers_composite_with_porter_duff_and_blend_modes() { + let half_red = [0.5, 0.0, 0.0, 0.5]; + assert_eq!(composite(CompositeMode::SrcOver, BLUE, half_red), [0.5, 0.0, 0.5, 1.0]); + assert_eq!(composite(CompositeMode::DestOver, BLUE, half_red), BLUE); + assert_eq!(composite(CompositeMode::SrcIn, [0.0; 4], RED), [0.0; 4]); + assert_eq!(composite(CompositeMode::DestOut, BLUE, RED), [0.0; 4]); + assert_eq!(composite(CompositeMode::Clear, BLUE, RED), [0.0; 4]); + assert_eq!(composite(CompositeMode::Plus, RED, BLUE), [1.0, 0.0, 1.0, 1.0]); + // Multiply of red and blue on opaque pixels is black. + assert_eq!(composite(CompositeMode::Multiply, BLUE, RED), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(composite(CompositeMode::Screen, BLUE, RED), [1.0, 0.0, 1.0, 1.0]); + } +} diff --git a/crates/text/src/color_tests.rs b/crates/text/src/color_tests.rs new file mode 100644 index 0000000000..1bcc88f1da --- /dev/null +++ b/crates/text/src/color_tests.rs @@ -0,0 +1,394 @@ +//! Colour glyphs (COLR v0 and v1 with CPAL) draw in the font's colours (#7711). The fonts are +//! Inter with a COLR and a CPAL table spliced in, so no colour font has to be bundled. + +use std::sync::Arc; + +use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; +use photocraft_doc::TextLayer; +use photocraft_doc::text::{AntiAlias, CharStyle, TextRun}; +use photocraft_geom::Affine; +use skrifa::{FontRef, MetadataProvider}; + +use crate::render::{ink_rect, rasterize}; +use crate::{TextEngine, TextLayout, fonts}; + +/// `font` with extra tables, the table directory rebuilt in tag order. +fn with_tables(font: &[u8], extra: &[([u8; 4], Vec)]) -> Vec { + let be16 = |o: usize| u16::from_be_bytes([font[o], font[o + 1]]) as usize; + let be32 = |o: usize| u32::from_be_bytes([font[o], font[o + 1], font[o + 2], font[o + 3]]) as usize; + let mut tables: Vec<([u8; 4], Vec)> = (0..be16(4)) + .map(|i| { + let r = 12 + 16 * i; + let (off, len) = (be32(r + 8), be32(r + 12)); + ([font[r], font[r + 1], font[r + 2], font[r + 3]], font[off..off + len].to_vec()) + }) + .collect(); + tables.extend(extra.iter().cloned()); + tables.sort_by_key(|t| t.0); + let n = tables.len(); + let mut out = font[..4].to_vec(); + let pow = 1usize << (usize::BITS - 1 - n.leading_zeros()); + for v in [n, pow * 16, pow.trailing_zeros() as usize, n * 16 - pow * 16] { + out.extend_from_slice(&(v as u16).to_be_bytes()); + } + let offset = 12 + 16 * n; + let mut data = Vec::new(); + for (tag, body) in &tables { + out.extend_from_slice(tag); + out.extend_from_slice(&0u32.to_be_bytes()); + out.extend_from_slice(&((offset + data.len()) as u32).to_be_bytes()); + out.extend_from_slice(&(body.len() as u32).to_be_bytes()); + data.extend_from_slice(body); + data.resize(data.len().next_multiple_of(4), 0); + } + out.extend_from_slice(&data); + out +} + +/// A CPAL table with one palette of straight RGBA bytes. +fn cpal(colors: &[[u8; 4]]) -> Vec { + let mut t = Vec::new(); + for v in [0u16, colors.len() as u16, 1, colors.len() as u16] { + t.extend_from_slice(&v.to_be_bytes()); + } + t.extend_from_slice(&14u32.to_be_bytes()); + t.extend_from_slice(&0u16.to_be_bytes()); + for [r, g, b, a] in colors { + t.extend_from_slice(&[*b, *g, *r, *a]); + } + t +} + +/// A COLR v0 table: `base` drawn as `layers` (glyph, palette entry), bottom first. +fn colr_v0(base: u16, layers: &[(u16, u16)]) -> Vec { + let mut t = Vec::new(); + t.extend_from_slice(&0u16.to_be_bytes()); + t.extend_from_slice(&1u16.to_be_bytes()); + t.extend_from_slice(&14u32.to_be_bytes()); + t.extend_from_slice(&20u32.to_be_bytes()); + t.extend_from_slice(&(layers.len() as u16).to_be_bytes()); + for v in [base, 0, layers.len() as u16] { + t.extend_from_slice(&v.to_be_bytes()); + } + for (g, p) in layers { + t.extend_from_slice(&g.to_be_bytes()); + t.extend_from_slice(&p.to_be_bytes()); + } + t +} + +/// A COLR v1 table: `base` is its own outline filled with a linear gradient from palette entry 0 +/// at x = `x0` to entry 1 at x = `x1` (font units). +fn colr_v1_gradient(base: u16, x0: i16, x1: i16) -> Vec { + let mut t = Vec::new(); + // Header: version 1, no v0 records, then the BaseGlyphList right after the 34-byte header. + t.extend_from_slice(&1u16.to_be_bytes()); + t.extend_from_slice(&0u16.to_be_bytes()); + t.extend_from_slice(&0u32.to_be_bytes()); + t.extend_from_slice(&0u32.to_be_bytes()); + t.extend_from_slice(&0u16.to_be_bytes()); + t.extend_from_slice(&34u32.to_be_bytes()); + for _ in 0..4 { + t.extend_from_slice(&0u32.to_be_bytes()); + } + // BaseGlyphList: one record, its paint 10 bytes in. + t.extend_from_slice(&1u32.to_be_bytes()); + t.extend_from_slice(&base.to_be_bytes()); + t.extend_from_slice(&10u32.to_be_bytes()); + // PaintGlyph (format 10): the child paint 6 bytes in, clipped to `base`. + t.extend_from_slice(&[10, 0, 0, 6]); + t.extend_from_slice(&base.to_be_bytes()); + // PaintLinearGradient (format 4): colour line 16 bytes in; p0, p1, p2 (p2 above p0). + t.extend_from_slice(&[4, 0, 0, 16]); + for v in [x0, 0, x1, 0, x0, 1000] { + t.extend_from_slice(&v.to_be_bytes()); + } + // ColorLine: pad, two stops (offset, palette entry, alpha), F2Dot14. + t.push(0); + t.extend_from_slice(&2u16.to_be_bytes()); + for (offset, entry) in [(0i16, 0u16), (1 << 14, 1)] { + t.extend_from_slice(&offset.to_be_bytes()); + t.extend_from_slice(&entry.to_be_bytes()); + t.extend_from_slice(&(1i16 << 14).to_be_bytes()); + } + t +} + +fn gid(font: &[u8], c: char) -> u16 { + let f = FontRef::new(font).expect("Inter parses"); + f.charmap().map(c).map_or(0, |g| g.to_u32() as u16) +} + +const RED: [u8; 4] = [255, 0, 0, 255]; +const BLUE: [u8; 4] = [0, 0, 255, 255]; + +/// `text` laid out in Inter at 72 dpi, then drawn with `font` (Inter plus colour tables). +fn layout_with(text: &str, font: Vec, color: Color) -> TextLayout { + let mut e = TextEngine::new(); + let style = CharStyle { size_pt: 64.0, color, ..Default::default() }; + let layer = TextLayer { text: text.into(), font_family: "Inter".into(), runs: vec![TextRun { len: text.len(), style }], ..Default::default() }; + let mut l = e.layout(&layer, 72.0); + for f in &mut l.faces { + f.font = parley::FontData::new(parley::fontique::Blob::new(Arc::new(font.clone())), 0); + } + l +} + +/// Straight RGBA of every covered pixel, as RGB whatever the format. +fn pixels(l: &TextLayout, format: PixelFormat) -> Vec<[f32; 4]> { + let r = rasterize(l, &Affine::IDENTITY, format, AntiAlias::Sharp); + let data = r.surface.read_region(r.rect); + let n = format.channels(); + data.chunks_exact(n) + .map(|p| { + let a = p[n - 1]; + let rgb = match format.mode { + ColorMode::Grayscale => [p[0]; 3], + _ => [p[0], p[1], p[2]], + }; + [rgb[0], rgb[1], rgb[2], a] + }) + .collect() +} + +fn depths() -> [PixelFormat; 3] { + [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] +} + +#[test] +fn colr_v0_layers_take_their_palette_colours_not_the_text_colour() { + let inter = fonts::INTER_REGULAR.as_slice(); + let (h, i) = (gid(inter, 'H'), gid(inter, 'I')); + // H is red; an I on top takes the text colour (palette entry 0xFFFF). + let font = with_tables(inter, &[(*b"COLR", colr_v0(h, &[(h, 0), (i, 0xFFFF)])), (*b"CPAL", cpal(&[RED]))]); + let green = Color::rgb(0.0, 1.0, 0.0); + for format in depths() { + let px = pixels(&layout_with("H", font.clone(), green), format); + let solid: Vec<_> = px.iter().filter(|p| p[3] > 0.99).collect(); + assert!(!solid.is_empty(), "{format:?}: nothing drawn"); + let red = solid.iter().filter(|p| p[0] > 0.98 && p[1] < 0.02 && p[2] < 0.02).count(); + let fg = solid.iter().filter(|p| p[1] > 0.98 && p[0] < 0.02 && p[2] < 0.02).count(); + assert!(red > 50, "{format:?}: {red} red pixels"); + assert!(fg > 20, "{format:?}: {fg} pixels in the text colour"); + // The rest are the I's anti-aliased edge over the red: mixes of the two, nothing else. + assert!(solid.len() - red - fg < 20, "{format:?}: {} mixed pixels", solid.len() - red - fg); + assert!(solid.iter().all(|p| p[2] < 0.02 && (p[0] + p[1] - 1.0).abs() < 0.03), "{format:?}: a colour that is neither"); + } + // Without the colour tables the same glyph is all text colour. + let px = pixels(&layout_with("H", inter.to_vec(), green), PixelFormat::RGBA8); + assert!(px.iter().filter(|p| p[3] > 0.99).all(|p| p[1] > 0.98 && p[0] < 0.02)); +} + +#[test] +fn colour_glyph_takes_the_text_colours_opacity_and_any_colour_mode() { + let inter = fonts::INTER_REGULAR.as_slice(); + let h = gid(inter, 'H'); + let font = with_tables(inter, &[(*b"COLR", colr_v0(h, &[(h, 0)])), (*b"CPAL", cpal(&[RED]))]); + let px = pixels(&layout_with("H", font.clone(), Color::rgba(0.0, 0.0, 0.0, 0.5)), PixelFormat::RGBA8); + let top = px.iter().map(|p| p[3]).fold(0.0, f32::max); + assert!((top - 0.5).abs() < 0.01, "max alpha {top}"); + assert!(px.iter().filter(|p| p[3] > 0.1).all(|p| p[0] > 0.98 && p[1] < 0.02), "red at half opacity"); + // Grayscale documents get the red's grey. + let gray = PixelFormat::new(ColorMode::Grayscale, SampleType::U16, true); + let px = pixels(&layout_with("H", font, Color::BLACK), gray); + let solid: Vec<_> = px.iter().filter(|p| p[3] > 0.99).collect(); + assert!(!solid.is_empty() && solid.iter().all(|p| p[0] > 0.1 && p[0] < 0.6), "{:?}", solid.first()); +} + +#[test] +fn colour_glyph_ink_covers_its_layers() { + let inter = fonts::INTER_REGULAR.as_slice(); + let (i, w) = (gid(inter, 'I'), gid(inter, 'W')); + // A narrow I drawn as a wide W: the layer's ink is the glyph's ink. + let font = with_tables(inter, &[(*b"COLR", colr_v0(i, &[(w, 0)])), (*b"CPAL", cpal(&[RED]))]); + let plain = ink_rect(&layout_with("I", inter.to_vec(), Color::BLACK), &Affine::IDENTITY); + let colour = ink_rect(&layout_with("I", font.clone(), Color::BLACK), &Affine::IDENTITY); + assert!(colour.width() > plain.width() * 3, "{plain:?} vs {colour:?}"); + let px = pixels(&layout_with("I", font, Color::BLACK), PixelFormat::RGBA8); + assert!(px.iter().filter(|p| p[3] > 0.99).count() > 400); +} + +#[test] +fn colr_v1_gradient_runs_across_the_glyph() { + let inter = fonts::INTER_REGULAR.as_slice(); + let h = gid(inter, 'H'); + let upem = + FontRef::new(inter).map(|f| f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()).units_per_em).unwrap_or(2048); + let font = with_tables(inter, &[(*b"COLR", colr_v1_gradient(h, 0, upem as i16 * 3 / 4)), (*b"CPAL", cpal(&[RED, BLUE]))]); + for format in depths() { + let l = layout_with("H", font.clone(), Color::BLACK); + let r = rasterize(&l, &Affine::IDENTITY, format, AntiAlias::Sharp); + let w = r.rect.width() as usize; + let data = r.surface.read_region(r.rect); + let px: Vec<[f32; 4]> = data.as_chunks::<4>().0.to_vec(); + // The leftmost opaque column is mostly red, the rightmost mostly blue, with no green. + let opaque: Vec<(usize, [f32; 4])> = px.iter().enumerate().filter(|(_, p)| p[3] > 0.99).map(|(i, p)| (i % w, *p)).collect(); + let (lo, hi) = (opaque.iter().map(|o| o.0).min().unwrap_or(0), opaque.iter().map(|o| o.0).max().unwrap_or(0)); + assert!(hi > lo + 10, "{format:?}: drawn {lo}..{hi}"); + for (x, p) in &opaque { + assert!(p[1] < 0.02, "{format:?}: green at {x}"); + if *x == lo { + assert!(p[0] > 0.8 && p[2] < 0.2, "{format:?}: left {p:?}"); + } + if *x == hi { + assert!(p[2] > 0.8 && p[0] < 0.2, "{format:?}: right {p:?}"); + } + } + } +} + +/// A COLR v1 table whose `base` paints itself (PaintColrGlyph), a cycle skrifa refuses to walk. +fn colr_v1_cycle(base: u16) -> Vec { + let mut t = Vec::new(); + for v in [1u16, 0] { + t.extend_from_slice(&v.to_be_bytes()); + } + t.extend_from_slice(&0u32.to_be_bytes()); + t.extend_from_slice(&0u32.to_be_bytes()); + t.extend_from_slice(&0u16.to_be_bytes()); + t.extend_from_slice(&34u32.to_be_bytes()); + for _ in 0..4 { + t.extend_from_slice(&0u32.to_be_bytes()); + } + t.extend_from_slice(&1u32.to_be_bytes()); + t.extend_from_slice(&base.to_be_bytes()); + t.extend_from_slice(&10u32.to_be_bytes()); + // PaintColrGlyph (format 11) of itself. + t.push(11); + t.extend_from_slice(&base.to_be_bytes()); + t +} + +#[test] +fn a_colour_glyph_skrifa_cannot_walk_draws_its_outline() { + // A paint graph that loops back on itself fails in skrifa; the glyph keeps its plain + // outline in the text colour instead of vanishing. + let inter = fonts::INTER_REGULAR.as_slice(); + let h = gid(inter, 'H'); + let font = with_tables(inter, &[(*b"COLR", colr_v1_cycle(h)), (*b"CPAL", cpal(&[RED]))]); + let green = Color::rgb(0.0, 1.0, 0.0); + let px = pixels(&layout_with("H", font, green), PixelFormat::RGBA8); + let solid: Vec<_> = px.iter().filter(|p| p[3] > 0.99).collect(); + assert!(solid.len() > 100, "{} pixels", solid.len()); + assert!(solid.iter().all(|p| p[1] > 0.98 && p[0] < 0.02), "{:?}", solid.first()); +} + +#[test] +fn a_colour_glyph_without_a_base_outline_still_paints() { + // The base glyph has no outline of its own (no glyf entry); its colour layer does. + let inter = fonts::INTER_REGULAR.as_slice(); + let h = gid(inter, 'H'); + let base = 60000u16; + let font = with_tables(inter, &[(*b"COLR", colr_v0(base, &[(h, 0)])), (*b"CPAL", cpal(&[RED]))]); + assert!(FontRef::new(&font).is_ok_and(|f| f.outline_glyphs().get(skrifa::GlyphId::new(base.into())).is_none())); + let mut l = layout_with("H", font, Color::BLACK); + for g in &mut l.glyphs { + g.id = base.into(); + } + let px = pixels(&l, PixelFormat::RGBA8); + let red = px.iter().filter(|p| p[3] > 0.99 && p[0] > 0.98 && p[1] < 0.02).count(); + assert!(red > 100, "{red} red pixels"); +} + +#[test] +fn colour_glyphs_keep_extended_text_colours_in_float_documents() { + // A layer in the text colour (palette entry 0xFFFF) keeps HDR and signed components in a + // float document, as plain glyphs do, and stays bounded in integer ones. + let inter = fonts::INTER_REGULAR.as_slice(); + let h = gid(inter, 'H'); + let font = with_tables(inter, &[(*b"COLR", colr_v0(h, &[(h, 0xFFFF)])), (*b"CPAL", cpal(&[RED]))]); + let color = Color::rgba(2.5, -0.25, 0.5, 1.0); + let float = pixels(&layout_with("H", font.clone(), color), PixelFormat::RGBA32F); + let covered: Vec<_> = float.iter().filter(|p| p[3] > 0.01).collect(); + assert!(covered.len() > 100); + assert!(covered.iter().all(|p| (p[0] - 2.5).abs() < 1e-4 && (p[1] + 0.25).abs() < 1e-4), "{:?}", covered.first()); + let int = pixels(&layout_with("H", font, color), PixelFormat::RGBA8); + assert!(int.iter().filter(|p| p[3] > 0.01).all(|p| p[0] == 1.0 && p[1] == 0.0)); +} + +/// A COLR v1 table whose `base` paints `paint` (format bytes, offsets relative to each table). +fn colr_v1(base: u16, paint: &[u8]) -> Vec { + let mut t = Vec::new(); + for v in [1u16, 0] { + t.extend_from_slice(&v.to_be_bytes()); + } + t.extend_from_slice(&0u32.to_be_bytes()); + t.extend_from_slice(&0u32.to_be_bytes()); + t.extend_from_slice(&0u16.to_be_bytes()); + t.extend_from_slice(&34u32.to_be_bytes()); + for _ in 0..4 { + t.extend_from_slice(&0u32.to_be_bytes()); + } + t.extend_from_slice(&1u32.to_be_bytes()); + t.extend_from_slice(&base.to_be_bytes()); + t.extend_from_slice(&10u32.to_be_bytes()); + t.extend_from_slice(paint); + t +} + +/// `depth` PaintComposites, each with the next one as both its source and its backdrop, over +/// `base` filled with palette entry `entry`: 2^depth fills from a few dozen bytes. +fn fan_out(base: u16, depth: usize, entry: u16) -> Vec { + let mut p = Vec::new(); + for _ in 0..depth { + // PaintComposite (format 32): source 8 bytes in, SrcOver, backdrop 8 bytes in. + p.extend_from_slice(&[32, 0, 0, 8, 3, 0, 0, 8]); + } + // PaintGlyph (format 10) of `base`, then PaintSolid (format 2), alpha 1. + p.extend_from_slice(&[10, 0, 0, 6]); + p.extend_from_slice(&base.to_be_bytes()); + p.push(2); + p.extend_from_slice(&entry.to_be_bytes()); + p.extend_from_slice(&(1i16 << 14).to_be_bytes()); + p +} + +#[test] +fn a_colour_glyph_that_fans_out_draws_its_outline() { + // A small graph that reuses both children of every composite would be walked 65536 times + // over (for the bounds, the ink and the paint); skrifa stops after a fixed number of paints + // and the glyph keeps its plain outline, as with a cycle. + let inter = fonts::INTER_REGULAR.as_slice(); + let h = gid(inter, 'H'); + let font = with_tables(inter, &[(*b"COLR", colr_v1(h, &fan_out(h, 16, 0))), (*b"CPAL", cpal(&[RED]))]); + let green = Color::rgb(0.0, 1.0, 0.0); + let px = pixels(&layout_with("H", font, green), PixelFormat::RGBA8); + let solid: Vec<_> = px.iter().filter(|p| p[3] > 0.99).collect(); + assert!(solid.len() > 100, "{} pixels", solid.len()); + assert!(solid.iter().all(|p| p[1] > 0.98 && p[0] < 0.02), "{:?}", solid.first()); +} + +#[test] +fn a_hidden_colour_glyph_does_not_spend_the_visible_texts_budget() { + // A huge colour H at opacity 0 whose paint alone would overrun the pixel budget, then a + // plain I in green: the H paints nothing anyway, and the I still shows. + let inter = fonts::INTER_REGULAR.as_slice(); + let h = gid(inter, 'H'); + let font = with_tables(inter, &[(*b"COLR", colr_v1(h, &fan_out(h, 11, 0))), (*b"CPAL", cpal(&[RED]))]); + let style = |color| CharStyle { size_pt: 600.0, color, ..Default::default() }; + let runs = vec![TextRun { len: 1, style: style(Color::TRANSPARENT) }, TextRun { len: 1, style: style(Color::rgb(0.0, 1.0, 0.0)) }]; + let layer = TextLayer { text: "HI".into(), font_family: "Inter".into(), runs, ..Default::default() }; + let mut l = TextEngine::new().layout(&layer, 72.0); + for f in &mut l.faces { + f.font = parley::FontData::new(parley::fontique::Blob::new(Arc::new(font.clone())), 0); + } + let px = pixels(&l, PixelFormat::RGBA8); + let green = px.iter().filter(|p| p[3] > 0.99 && p[1] > 0.98 && p[0] < 0.02).count(); + assert!(green > 1000, "{green} green pixels"); + assert!(px.iter().all(|p| p[3] < 0.01 || p[0] < 0.02), "the hidden H showed"); +} + +#[test] +fn colour_glyph_layers_in_the_text_colour_keep_its_cmyk_components() { + // In a CMYK document a K-only text colour stays K only in a 0xFFFF layer, as in plain text, + // instead of coming back from sRGB as a four-colour black. + let inter = fonts::INTER_REGULAR.as_slice(); + let h = gid(inter, 'H'); + let font = with_tables(inter, &[(*b"COLR", colr_v0(h, &[(h, 0xFFFF)])), (*b"CPAL", cpal(&[RED]))]); + let k = Color { mode: ColorMode::Cmyk, c: [0.0, 0.0, 0.0, 1.0], alpha: 1.0 }; + let r = rasterize(&layout_with("H", font, k), &Affine::IDENTITY, PixelFormat::CMYKA8, AntiAlias::Sharp); + let data = r.surface.read_region(r.rect); + let solid: Vec<&[f32; 5]> = data.as_chunks::<5>().0.iter().filter(|p| p[4] > 0.99).collect(); + assert!(solid.len() > 100, "{} pixels", solid.len()); + assert!(solid.iter().all(|p| p[0] < 0.01 && p[1] < 0.01 && p[2] < 0.01 && p[3] > 0.99), "{:?}", solid.first()); +} diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index 416ae7834c..489f2eef5e 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -295,6 +295,12 @@ impl FontDb { self.register_blob(Blob::new(Arc::new(bytes)), None) } + /// [`Self::register_font_data`] with the family name overridden, so an embedded subset can be + /// registered under a name that cannot shadow an installed full family. Returns the names added. + pub fn register_font_data_as(&mut self, bytes: Vec, family: &str) -> Vec { + self.register_blob(Blob::new(Arc::new(bytes)), Some(family)) + } + /// Registers embedded font data without copying it. fn register_static_font(&mut self, bytes: &'static [u8]) -> Vec { self.register_blob(Blob::new(Arc::new(bytes)), None) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 4a4219e143..9764be6aa5 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -19,6 +19,7 @@ pub mod area; pub mod cjk; +mod color_glyphs; pub mod craft_fonts; mod embolden; pub mod engine_data; @@ -142,6 +143,22 @@ impl TextEngine { layer.cache = Some(r.surface); r.rect } + + /// Registers font bytes (for example a font embedded in an imported PDF) for later layout. + /// Returns the family names the font provides, best first. + pub fn register_font_data(&mut self, bytes: Vec) -> Vec { + self.fonts.register_font_data(bytes) + } + + /// [`Self::register_font_data`] under `family`, which cannot shadow an installed family. + pub fn register_font_data_as(&mut self, bytes: Vec, family: &str) -> Vec { + self.fonts.register_font_data_as(bytes, family) + } + + /// Whether `family` is available to this engine. + pub fn has_family(&mut self, family: &str) -> bool { + self.fonts.has_family(family) + } } static SHARED: warm::Warm> = warm::Warm::new(); @@ -310,6 +327,8 @@ mod warm { } } +#[cfg(test)] +mod color_tests; #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/text/src/raster.rs b/crates/text/src/raster.rs index 4f32e9941e..e18de08ae3 100644 --- a/crates/text/src/raster.rs +++ b/crates/text/src/raster.rs @@ -17,6 +17,16 @@ impl Xform { let [oa, ob, oc, od, oe, of] = o.0; Xform([a * oa + c * ob, b * oa + d * ob, a * oc + c * od, b * oc + d * od, a * oe + c * of + e, b * oe + d * of + f]) } + /// The inverse map, `None` when singular or not finite. + pub fn invert(&self) -> Option { + let [a, b, c, d, e, f] = self.0; + let det = a * d - b * c; + if !det.is_finite() || det.abs() < 1e-12 { + return None; + } + let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det); + Some(Xform([ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)])) + } /// Largest scale factor (for flattening tolerance). pub fn max_scale(&self) -> f64 { let [a, b, c, d, ..] = self.0; diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index ffc595aab8..5da337235e 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -1,6 +1,6 @@ //! Rasterizes a [`TextLayout`] into a document-space [`Surface`] of any pixel format. -use photocraft_color::{Color, PixelFormat, SampleType}; +use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::text::AntiAlias; use photocraft_geom::{Affine, Rect}; use photocraft_raster::Surface; @@ -8,6 +8,7 @@ use skrifa::instance::{LocationRef, NormalizedCoord, Size}; use skrifa::outline::DrawSettings; use skrifa::{GlyphId, MetadataProvider}; +use crate::color_glyphs::{Ink, Limits, NoPaint, OutlineBounds, Painter, Shape}; use crate::layout::{DecorationRect, GlyphOrient, PlacedGlyph, TextLayout}; use crate::raster::{Bounds, Coverage, LineSink, Pen, Xform, rect_to}; use crate::warp::{Placement, Warp}; @@ -17,10 +18,15 @@ use rayon::prelude::*; /// Faux-italic slant in degrees (Photoshop-like). pub const FAUX_ITALIC_DEG: f32 = 12.0; -/// How far faux bold grows the outline on every side, as a fraction of the font size -/// ([`crate::embolden`]): stems get twice this heavier, close to the weight of the earlier -/// faux bold, which stamped the glyph at offsets of this radius. -pub const FAUX_BOLD_RADIUS: f32 = 0.036; +/// How far faux bold grows the outline on every side, in pixels (`crate::embolden`): stems get +/// twice this heavier. Photoshop thickens by about `size/72`; the flat 3.6% of the size used +/// before overshot its ink by 1.3–1.5× from 50 px up. So the ring follows the size, with a pixel +/// floor that fades in below ~32 px (Photoshop's small type reads heavier than `size/72`) and a +/// cap so a sub-pixel glyph does not grow into a blob. +pub fn faux_bold_radius(size_px: f32) -> f32 { + (size_px / 72.0).max((size_px / 40.0).min(0.45)) +} + /// Largest raster we produce (pixels), as a guard against absurd sizes. const MAX_PIXELS: u64 = 256 * 1024 * 1024; /// Cumulative coverage-pixel work budget across the colour passes of one render. @@ -61,7 +67,7 @@ fn nothing(format: PixelFormat) -> Rendered { /// Maps raw area-coverage to the opacity Photoshop's anti-alias modes imply. Exponents above 1 thin /// the fringe (sharper); below 1 widen it (stronger smoothing). -fn shape_antialias_coverage(cv: f32, mode: AntiAlias) -> f32 { +pub(crate) fn shape_antialias_coverage(cv: f32, mode: AntiAlias) -> f32 { if !cv.is_finite() { return 0.0; } @@ -123,14 +129,15 @@ fn glyph_is_placed(layout: &TextLayout, g: &PlacedGlyph, warp: Option<&Warp>) -> let Ok(font) = skrifa::FontRef::from_index(face.font.data.as_ref(), face.font.index) else { return false; }; - if font.outline_glyphs().get(GlyphId::new(g.id)).is_none() { + let coords: Vec = face.coords.iter().map(|&c| NormalizedCoord::from_bits(c)).collect(); + // A colour glyph paints its layers, so it counts even when its base glyph has no outline. + if font.outline_glyphs().get(GlyphId::new(g.id)).is_none() && color_glyph(&font, GlyphId::new(g.id), &coords).is_none() { return false; } - if let Some(w) = warp { - let coords: Vec = face.coords.iter().map(|&c| NormalizedCoord::from_bits(c)).collect(); - if matches!(w.place_glyph(glyph_center(layout, g, &font, face.size_px, &coords)), Placement::Hidden) { - return false; - } + if let Some(w) = warp + && matches!(w.place_glyph(glyph_center(layout, g, &font, face.size_px, &coords)), Placement::Hidden) + { + return false; } true } @@ -185,7 +192,7 @@ pub(crate) fn visible_color_passes(layout: &TextLayout, warp: Option<&Warp>) -> /// Draws the glyphs and decorations of `layout` in `only` (or all of them when it is `None`) into `sink`, through `transform` (text space → sink space), bending /// the outlines with `warp` first (in text space). Faux bold glyphs are drawn from their outline -/// thickened by [`FAUX_BOLD_RADIUS`] ([`crate::embolden`]). +/// thickened by [`faux_bold_radius`] ([`crate::embolden`]). fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only: Option<&Pass>, warp: Option<&Warp>) { let glyphs: Box> = match only { Some(p) => Box::new(p.glyphs.iter().filter_map(|&i| layout.glyphs.get(i))), @@ -197,23 +204,29 @@ fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only: let Ok(font) = skrifa::FontRef::from_index(face.font.data.as_ref(), face.font.index) else { continue; }; + let coords: Vec = face.coords.iter().map(|&c| NormalizedCoord::from_bits(c)).collect(); + // Colour glyphs paint in their own colours ([`paint_color_glyphs`]); only their extent + // counts here. + if let Some(color) = color_glyph(&font, GlyphId::new(g.id), &coords) { + if only.is_none() + && let Some((glyph, bend)) = place(layout, g, &font, face.size_px, &coords, warp) + { + let unit = font_units(&font, face.size_px, &coords, glyph); + let outline = |shape: Shape, m: &Xform, s: &mut Bounds| shape_into(&font, &coords, shape, unit.mul(m), transform, bend, s); + let mut b = Bounds::default(); + let _ = color.paint(LocationRef::new(&coords), &mut OutlineBounds::new(&mut b, outline)); + if let Some([x0, y0, x1, y1]) = b.rect { + rect_to(sink, &Xform::IDENTITY, x0, y0, x1, y1); + } + } + continue; + } let Some(outline) = font.outline_glyphs().get(GlyphId::new(g.id)) else { continue; }; - let coords: Vec = face.coords.iter().map(|&c| NormalizedCoord::from_bits(c)).collect(); - let mut glyph = glyph_xform(layout, g, face.skew_deg); - // Type on a path moves each glyph rigidly: turned to the curve at its centre. - let mut bend = warp; - if let Some(w) = warp { - match w.place_glyph(glyph_center(layout, g, &font, face.size_px, &coords)) { - Placement::Bend => {} - Placement::Hidden => continue, - Placement::Frame(m) => { - glyph = Xform(m).mul(&glyph); - bend = None; - } - } - } + let Some((glyph, bend)) = place(layout, g, &font, face.size_px, &coords, warp) else { + continue; + }; let settings = || DrawSettings::unhinted(Size::new(face.size_px), LocationRef::new(&coords)); // Faux bold thickens the outline in font units, before faux italic and scaling, so the // slant and proportions apply to the bold shape as they do to a real bold face. Other @@ -224,7 +237,7 @@ fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only: if outline.draw(settings(), &mut shape).is_err() { continue; } - shape.embolden(f64::from(face.size_px * FAUX_BOLD_RADIUS)); + shape.embolden(f64::from(faux_bold_radius(face.size_px))); bold = Some(shape); } let settings = settings(); @@ -251,6 +264,178 @@ fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only: } } +/// Where a placed glyph goes: its outline map (px-scaled font units, y up → text space) and the +/// warp still to bend it with. `None` when type on a path hides it. +fn place<'w>( + layout: &TextLayout, + g: &PlacedGlyph, + font: &skrifa::FontRef, + size_px: f32, + coords: &[NormalizedCoord], + warp: Option<&'w Warp>, +) -> Option<(Xform, Option<&'w Warp>)> { + let face_skew = layout.faces.get(g.face as usize).map_or(0.0, |f| f.skew_deg); + let glyph = glyph_xform(layout, g, face_skew); + // Type on a path moves each glyph rigidly: turned to the curve at its centre. + match warp.map(|w| w.place_glyph(glyph_center(layout, g, font, size_px, coords))) { + None | Some(Placement::Bend) => Some((glyph, warp)), + Some(Placement::Hidden) => None, + Some(Placement::Frame(m)) => Some((Xform(m).mul(&glyph), None)), + } +} + +/// `glyph` (see [`place`]) for unscaled font units, as colour glyphs paint in. +fn font_units(font: &skrifa::FontRef, size_px: f32, coords: &[NormalizedCoord], glyph: Xform) -> Xform { + let upem = font.metrics(Size::unscaled(), LocationRef::new(coords)).units_per_em; + let k = if upem > 0 { f64::from(size_px) / f64::from(upem) } else { 0.0 }; + glyph.mul(&Xform([k, 0.0, 0.0, k, 0.0, 0.0])) +} + +/// Draws `outline` through `local` (font space → text space), bent by `bend`, then mapped by +/// `transform` into `sink`. +fn draw_outline( + outline: &skrifa::outline::OutlineGlyph, + settings: DrawSettings, + local: Xform, + transform: &Xform, + bend: Option<&Warp>, + sink: &mut impl LineSink, +) { + match bend { + Some(w) => { + let mut ws = WarpSink { inner: sink, warp: w, post: *transform }; + let mut pen = Pen::new(&mut ws, local); + if outline.draw(settings, &mut pen).is_ok() { + skrifa::outline::OutlinePen::close(&mut pen); + } + } + None => { + let mut pen = Pen::new(sink, transform.mul(&local)); + if outline.draw(settings, &mut pen).is_ok() { + skrifa::outline::OutlinePen::close(&mut pen); + } + } + } +} + +/// The colour glyph `id` paints as, when the font has one and skrifa can walk its paint graph. +/// A graph it cannot walk (too deep, a cycle, a broken offset) leaves the glyph to its plain +/// outline in the text colour instead of dropping it. +fn color_glyph<'a>(font: &skrifa::FontRef<'a>, id: GlyphId, coords: &[NormalizedCoord]) -> Option> { + let color = font.color_glyphs().get(id)?; + color.paint(LocationRef::new(coords), &mut NoPaint).is_ok().then_some(color) +} + +/// A colour glyph's clip [`Shape`], unscaled font units through `local` (font units → text +/// space), into `sink`: a glyph's outline, or a clip box, bent by `bend` like the outlines so it +/// still crops what it was meant to. +fn shape_into( + font: &skrifa::FontRef, + coords: &[NormalizedCoord], + shape: Shape, + local: Xform, + transform: &Xform, + bend: Option<&Warp>, + sink: &mut impl LineSink, +) { + match shape { + Shape::Glyph(id) => { + if let Some(outline) = font.outline_glyphs().get(id) { + draw_outline(&outline, DrawSettings::unhinted(Size::unscaled(), LocationRef::new(coords)), local, transform, bend, sink); + } + } + Shape::Box(b) => { + let (x0, y0, x1, y1) = (f64::from(b.x_min), f64::from(b.y_min), f64::from(b.x_max), f64::from(b.y_max)); + match bend { + Some(w) => rect_to(&mut WarpSink { inner: sink, warp: w, post: *transform }, &local, x0, y0, x1, y1), + None => rect_to(sink, &transform.mul(&local), x0, y0, x1, y1), + } + } + } +} + +/// Paints the colour glyphs of `layout` in their own colours over the premultiplied accumulator +/// (`w × h`, `format`'s colour channels then alpha): their palette's sRGB converted to the +/// document's colour model, times the text colour's opacity. `None` when a glyph's buffers could +/// not be reserved or `limits` ran out (see [`Limits`]). +#[allow(clippy::too_many_arguments)] +fn paint_color_glyphs( + layout: &TextLayout, + xf: &Xform, + warp: Option<&Warp>, + format: &PixelFormat, + antialias: AntiAlias, + acc: &mut [f32], + (w, h): (usize, usize), + mut limits: Limits, +) -> Option<()> { + let n = format.mode.color_channels(); + let stride = n + 1; + let opaque = PixelFormat { alpha: false, ..*format }; + // Float documents keep extended (HDR, signed) colours, as the plain passes do. + let keep_range = |v: f32| if format.sample == SampleType::F32 && v.is_finite() { v } else { v.clamp(0.0, 1.0) }; + for g in &layout.glyphs { + let (Some(st), Some(face)) = (layout.styles.get(g.style as usize), layout.faces.get(g.face as usize)) else { continue }; + // A glyph the text colour's opacity hides paints nothing; walking it would only spend the + // budget the visible text needs (as the plain passes skip it, `visible_color_passes`). + let opacity = st.color.alpha.clamp(0.0, 1.0); + if opacity.is_nan() || opacity <= 0.0 { + continue; + } + let Ok(font) = skrifa::FontRef::from_index(face.font.data.as_ref(), face.font.index) else { continue }; + let coords: Vec = face.coords.iter().map(|&c| NormalizedCoord::from_bits(c)).collect(); + let Some(color) = color_glyph(&font, GlyphId::new(g.id), &coords) else { continue }; + let Some((glyph, bend)) = place(layout, g, &font, face.size_px, &coords, warp) else { continue }; + let unit = font_units(&font, face.size_px, &coords, glyph); + // The window the glyph can paint: its fills within their clips. + let mut b = Bounds::default(); + let outline = |shape: Shape, m: &Xform, s: &mut Bounds| shape_into(&font, &coords, shape, unit.mul(m), xf, bend, s); + if color.paint(LocationRef::new(&coords), &mut OutlineBounds::new(&mut b, outline)).is_err() { + continue; + } + let Some([x0, y0, x1, y1]) = b.rect else { continue }; + let clamp = |v: f64, hi: usize| v.clamp(0.0, hi as f64) as usize; + let (wx0, wy0, wx1, wy1) = (clamp(x0.floor() - 1.0, w), clamp(y0.floor() - 1.0, h), clamp(x1.ceil() + 1.0, w), clamp(y1.ceil() + 1.0, h)); + if wx1 <= wx0 || wy1 <= wy0 { + continue; + } + let (ww, wh) = (wx1 - wx0, wy1 - wy0); + let to_window = Xform([1.0, 0.0, 0.0, 1.0, -(wx0 as f64), -(wy0 as f64)]).mul(xf); + let palettes = font.color_palettes(); + let palette = palettes.get(0); + let [r, gr, bl] = st.color.to_rgb(); + // Pixels in the text colour alone keep its own components, as plain glyphs do (a CMYK + // black stays K only instead of coming back from sRGB as a four-colour black). + let native = (format.mode != ColorMode::Rgb).then(|| color_in(format, &st.color)); + let outline = |shape: Shape, m: &Xform, s: &mut Coverage| shape_into(&font, &coords, shape, unit.mul(m), &to_window, bend, s); + let ink = Ink { palette: palette.as_ref().map_or(&[][..], |p| p.colors()), foreground: [r, gr, bl, 1.0] }; + let mut painter = Painter::new(ww, wh, outline, to_window.mul(&unit), ink, antialias, limits); + if color.paint(LocationRef::new(&coords), &mut painter).is_err() { + continue; + } + // Compositing the window into the text is one more pass over it. + limits.work = painter.work_left().checked_sub((ww as u64).checked_mul(wh as u64)?)?; + for (i, s) in painter.finish()?.iter().enumerate() { + let a = s[3] * opacity; + let o = ((wy0 + i / ww) * w + wx0 + i % ww) * stride; + let (true, Some(px)) = (a > 0.0, acc.get_mut(o..o + stride)) else { continue }; + let straight = [s[0] / s[3], s[1] / s[3], s[2] / s[3]]; + let rgb = straight.map(keep_range); + let comps = match &native { + None => rgb.to_vec(), + Some(c) if straight.iter().zip([r, gr, bl]).all(|(v, f)| (v - f).abs() < 1e-5) => c.iter().copied().map(keep_range).collect(), + Some(_) => photocraft_raster::from_rgba(&opaque, [rgb[0], rgb[1], rgb[2], 1.0]), + }; + let keep = 1.0 - a; + for (p, c) in px.iter_mut().zip(&comps).take(n) { + *p = c * a + *p * keep; + } + px[n] = a + px[n] * keep; + } + } + Some(()) +} + /// One glyph into `pen`: its thickened `bold` outline when there is one, else the font's own. fn draw_glyph( outline: &skrifa::outline::OutlineGlyph, @@ -438,6 +623,13 @@ pub(crate) fn rasterize_passes( let a = c.alpha.clamp(0.0, 1.0); composite(&mut acc, w, sub, &cov, stride, &comps, a, antialias); } + // Colour glyphs get what the plain passes left of both budgets: the bytes beside the + // accumulator and the output surface ([`fits_raster_budget`]), and the pixel work. + let deep = (w as u64).saturating_mul(h as u64).saturating_mul(stride as u64).saturating_mul(size_of::() as u64 + format.sample.bytes() as u64); + let limits = Limits { bytes: MAX_RASTER_BYTES.saturating_sub(deep), work: MAX_PASS_PIXELS.saturating_sub(pass_pixels) }; + if paint_color_glyphs(layout, &xf, warp, &format, antialias, &mut acc, (w, h), limits).is_none() { + return nothing(format); + } // Unpremultiply. unpremultiply(&mut acc, n, stride, format.sample); surface.write_region_par(rect, &acc); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index a19d9d5208..cbd0c12a2c 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -573,14 +573,68 @@ fn faux_bold_keeps_antialiased_edges_at_small_sizes() { let (plain_ink, plain_partial) = stats(&mut e, base.clone()); let (bold_ink, bold_partial) = stats(&mut e, CharStyle { faux_bold: true, ..base }); assert!(bold_ink > plain_ink, "bold must add ink"); - // Weight: the old summed-coverage faux bold (before #4130) measured 282.7 total ink for this - // text at 12 px (plain 138.0). The antialiased version must stay close to that weight. - const MAIN_BOLD_INK: f64 = 282.7; - assert!(bold_ink >= MAIN_BOLD_INK * 0.85, "stems too thin: {bold_ink} vs old {MAIN_BOLD_INK}"); - assert!(bold_ink <= MAIN_BOLD_INK * 1.15, "stems too heavy: {bold_ink} vs old {MAIN_BOLD_INK}"); + // Weight: the ring is now `size/72` with a pixel floor (#9008), which is Photoshop's weight, + // so this guards the antialiased edges rather than the old, heavier 3.6% of the size. + const MAIN_BOLD_INK: f64 = 222.2; + assert!(bold_ink >= MAIN_BOLD_INK * 0.9, "stems too thin: {bold_ink} vs {MAIN_BOLD_INK}"); + assert!(bold_ink <= MAIN_BOLD_INK * 1.1, "stems too heavy: {bold_ink} vs {MAIN_BOLD_INK}"); assert!(bold_partial * 10 >= plain_partial * 8, "edges stay antialiased: {plain_partial} -> {bold_partial}"); } +/// #9008: the faux-bold ring is Photoshop's `size/72`, with a pixel floor that fades in below +/// ~32 px (Photoshop's small type reads heavier than that) and a cap so a glyph smaller than a +/// pixel does not grow into a blob. +#[test] +fn faux_bold_radius_has_a_pixel_floor_that_fades_for_tiny_type() { + let r = crate::render::faux_bold_radius; + assert!((r(300.0) - 300.0 / 72.0).abs() < 1e-3, "large type: {}", r(300.0)); + assert!((r(72.0) - 1.0).abs() < 1e-3, "72 px: {}", r(72.0)); + assert!((r(24.0) - 0.45).abs() < 1e-3, "the floor takes over below 32 px: {}", r(24.0)); + assert!((r(4.0) - 0.1).abs() < 1e-3, "and fades out for tiny type: {}", r(4.0)); + assert!(r(0.5) < 0.02, "sub-pixel type keeps a sub-pixel ring: {}", r(0.5)); + // Monotonic: heavier text never grows a thinner ring as it gets larger. + assert!((1..400).all(|px| r(px as f32) <= r(px as f32 + 1.0))); +} + +/// #9008: at display sizes the ring is `size/72`, so the extra ink is the outline's perimeter times +/// `2 * size/72` — not the flat 7.2% of the size that made a PSD's faux-bold layer jump heavier as +/// soon as clicking it re-rendered the text. +#[test] +fn faux_bold_at_display_sizes_grows_the_outline_by_size_over_72() { + let mut e = TextEngine::new(); + // Display sizes, including the two ends the issue reported on (75-125 px layers) and the + // sizes where the pixel floor hands over to `size/72` (32 px) and where the ring is 1 px + // (72 px). The flat 3.6% ring this replaces grew the outline by 0.072 * size instead, so a + // regression to it fails the width check at every size but 12 px. + let mut ratios = Vec::new(); + for px in [12.0f32, 32.0, 72.0, 120.0, 200.0] { + let ink = |e: &mut TextEngine, s: CharStyle| { + let (_, r) = e.render(&TextLayer { transform: Affine::translate(10.0, f64::from(px) * 1.4), ..styled("Hi", s) }, 72.0, PixelFormat::RGBA8); + (alpha_sum(&r.surface, r.rect), r.rect) + }; + let base = CharStyle { size_pt: px, ..Default::default() }; + let (plain, prect) = ink(&mut e, base.clone()); + let (bold, brect) = ink(&mut e, CharStyle { faux_bold: true, ..base }); + // The outline grows by the ring on every side, so the ink rectangle grows by twice it. + let ring = crate::render::faux_bold_radius(px); + let grew = (brect.width() - prect.width()) as f32; + assert!((grew - 2.0 * ring).abs() <= 1.5, "{px} px: width grew {grew}, expected about {}", 2.0 * ring); + // Heavier by the perimeter's worth of ink. Pinned per size, because a thicker ring here is + // exactly the jump a PSD's faux-bold layer shows when a click re-renders it. + ratios.push(bold / plain); + } + // Plain text's ink grows with the size, so the bold/plain ratio falls as the ring does relative + // to the stems: 1.9x at 12 px (the floor), about 1.35x at 120 px, 1.24x at 200 px. + // The ring is a fixed fraction of the size above the pixel floor, so the ratio does not move + // with the size: 1.35x at 32, 72, 120 and 200 px (the flat 3.6% ring measured 1.95x). At 12 px + // the floor is 3.75% of the size, so the type reads a little heavier, as Photoshop's does. + for (px, r) in [32.0f32, 72.0, 120.0, 200.0].iter().zip(&ratios[1..]) { + assert!((1.30..=1.40).contains(r), "{px} px: {r:.2}x, expected about 1.35x"); + } + assert!((1.55..=1.75).contains(&ratios[0]), "12 px: {:.2}x, expected about 1.64x", ratios[0]); + assert!(ratios[0] > ratios[4], "the pixel floor fades out: {:.2}x at 12 px, {:.2}x at 200 px", ratios[0], ratios[4]); +} + /// #3705: Faux bold dilation must scale with horizontal and vertical glyph scaling. #[test] fn faux_bold_scales_with_glyph_scaling() { @@ -3343,7 +3397,11 @@ fn per_colour_passes_match_full_size_passes() { px.chunks_exact(ch).flat_map(|p| p[..ch - 1].iter().map(|c| c * p[ch - 1]).chain([p[ch - 1]]).collect::>()).collect::>() }; let worst = shown(&a).iter().zip(&shown(&b)).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max); - assert!(worst <= 1.0 / 255.0, "case {k} {format:?}: largest difference {worst}"); + // Colour channels are 8-bit samples, so one step is 1/255. Coverage is accumulated in + // f32 from a buffer whose origin differs between the two paths, and a pixel sitting on + // a rounding tie then lands a step further out (measured 1.65/255 on the warped + // faux-bold case), so allow two steps. + assert!(worst <= 2.0 / 255.0, "case {k} {format:?}: largest difference {worst}"); } } } diff --git a/crates/ui-egui/examples/perf_scenarios.rs b/crates/ui-egui/examples/perf_scenarios.rs index 0ba257defd..1f25292897 100644 --- a/crates/ui-egui/examples/perf_scenarios.rs +++ b/crates/ui-egui/examples/perf_scenarios.rs @@ -1562,8 +1562,77 @@ fn full_layer_doc(w: u32, h: u32, depth: u32) -> Res<(Session, u64)> { Ok((s, layer)) } -/// #9329 PR A: the redraw area of edits on a full-canvas layer, where redrawing the whole -/// document is the expensive cliff. Each row checks it hits that path and prints `refresh px`. +/// The index of `layer` among the document's top-level layers (bottom first). +fn top_index(s: &Session, layer: u64) -> Res { + let doc = &s.active().ok_or("no document")?.doc; + doc.layers.iter().position(|l| l.id.0 == layer).ok_or_else(|| "layer is not top-level".to_string()) +} + +/// The composite pixel at (`x`, `y`). +fn composite_px(s: &Session, x: i32, y: i32) -> Res> { + let doc = &s.active().ok_or("no document")?.doc; + Ok(photocraft_compose::render(doc, Rect::new(x, y, x + 1, y + 1)).px.first().ok_or("empty render")?.to_vec()) +} + +/// #9329 PR B: the layered document with a Curves above panel 2, masked to a small rect inside +/// the panel. Returns the session, the Curves and a probe point inside the mask. +fn masked_curves_doc(w: u32, h: u32) -> Res<(Session, u64, (i32, i32))> { + let (mut s, _) = layered_doc(w, h)?; + let panel = s.active().ok_or("no document")?.doc.layers.iter().find(|l| l.name == "panel 2").map(|l| l.id.0).ok_or("no panel 2")?; + exec(&mut s, "layer.select", json!({"layer": panel}))?; + let (x, y, mw, mh) = (2 * w / 3 + w / 12, h / 8, w / 10, h / 10); + exec(&mut s, "select.rect", json!({"x": x, "y": y, "width": mw, "height": mh}))?; + let curves = + exec(&mut s, "layer.newAdjustmentLayer.curves", json!({"points": [[0, 0], [90, 170], [255, 255]]}))?["layer"].as_u64().ok_or("no curves id")?; + let doc = s.active().ok_or("no document")?.doc.clone(); + let above = doc.layers.len() - 1 - top_index(&s, curves)?; + if above < 4 { + return Err(format!("path check: {above} layers above the Curves, not >= 4 (the prefix cache would cover it)")); + } + let mask = doc.layer(photocraft_doc::LayerId(curves)).and_then(|l| l.mask.as_ref()).ok_or("path check: the Curves has no mask")?; + let share = coverage(&doc, mask.surface.content_bounds()); + if mask.value(0, 0) != 0.0 || share > 0.05 { + return Err(format!("path check: the mask reveals {:.2} % of the canvas, not <= 5 %", share * 100.0)); + } + let probe = ((x + mw / 2) as i32, (y + mh / 2) as i32); + let shown = composite_px(&s, probe.0, probe.1)?; + exec(&mut s, "layer.setProps", json!({"layer": curves, "visible": false}))?; + let hidden = composite_px(&s, probe.0, probe.1)?; + exec(&mut s, "layer.setProps", json!({"layer": curves, "visible": true}))?; + if shown == hidden { + return Err("path check: toggling the Curves changes no pixel inside its mask".into()); + } + Ok((s, curves, probe)) +} + +/// #9329 PR B: the many-layer document with a small layer added directly above `mid`, +/// overlapping it. Returns the session, `mid` and the neighbour. +fn reorder_doc(w: u32, h: u32, n: usize) -> Res<(Session, u64, u64)> { + let (mut s, mid) = many_layers_doc(w, h, n)?; + let mb = layer_bounds(&s, mid)?; + exec(&mut s, "layer.select", json!({"layer": mid}))?; + exec(&mut s, "layer.new.layer", json!({"name": "neighbour"}))?; + let next = active_layer(&s)?; + exec(&mut s, "select.rect", json!({"x": mb.x0 + mb.size().width as i32 / 3, "y": mb.y0 + mb.size().height as i32 / 3, "width": w / 10, "height": h / 10}))?; + exec(&mut s, "edit.fill", json!({"color": "#3050d0"}))?; + exec(&mut s, "select.deselect", json!({}))?; + exec(&mut s, "layer.select", json!({"layer": mid}))?; + let doc = s.active().ok_or("no document")?.doc.clone(); + let share = coverage(&doc, mb); + if share > 0.02 { + return Err(format!("path check: the layer covers {:.2} % of the canvas, not <= 2 %", share * 100.0)); + } + if top_index(&s, next)? != top_index(&s, mid)? + 1 { + return Err("path check: the neighbour is not directly above the layer".into()); + } + if layer_bounds(&s, next)?.intersect(&mb).is_empty() { + return Err("path check: the layer does not overlap the neighbour it passes".into()); + } + Ok((s, mid, next)) +} + +/// #9329: the redraw area of edits where redrawing the whole document is the expensive cliff +/// (PR A: full-canvas layers; PR B: a masked adjustment mid-stack and a reorder). Each row checks it hits that path and prints `refresh px`. fn redraw_area_scenarios(b: &mut Bench, sz: &Sizes) { let undo = "undo a brush dab on a full-canvas 16-bit 15000x10000 layer + refresh"; if b.wanted(undo) { @@ -1630,4 +1699,137 @@ fn redraw_area_scenarios(b: &mut Bench, sz: &Sizes) { } } } + + let toggle = "toggle a masked adjustment mid-stack in the layered document + refresh"; + if b.wanted(toggle) { + b.current = Some(toggle.to_string()); + let (w, h) = sz.layered; + match masked_curves_doc(w, h) { + Err(e) => b.errors.push((toggle.to_string(), e)), + Ok((mut s, curves, _)) => { + let _ = b.refresh(&s, true); + let reps = b.reps; + b.time(toggle, &mut s, reps, true, |b, s, i| { + let t = Instant::now(); + exec(s, "layer.setProps", json!({"layer": curves, "visible": i % 2 == 1}))?; + let took = ms(t) + b.refresh(s, false)?; + b.px.borrow_mut().push(b.last_px.get()); + Ok(took) + }); + } + } + } + + let reorder = "bring forward / send backward a small layer in the many-layer document + refresh"; + if b.wanted(reorder) { + b.current = Some(reorder.to_string()); + let (w, h) = sz.layered; + match reorder_doc(w, h, sz.many_layers) { + Err(e) => b.errors.push((reorder.to_string(), e)), + Ok((mut s, mid, _)) => { + let _ = b.refresh(&s, true); + let reps = b.reps; + b.time(reorder, &mut s, reps, true, |b, s, i| { + let before = top_index(s, mid)?; + let cmd = if i % 2 == 0 { "layer.arrange.bringForward" } else { "layer.arrange.sendBackward" }; + let t = Instant::now(); + exec(s, cmd, json!({"layer": mid}))?; + let took = ms(t) + b.refresh(s, false)?; + b.px.borrow_mut().push(b.last_px.get()); + if top_index(s, mid)? == before { + return Err("path check: the layer's index did not change".into()); + } + Ok(took) + }); + } + } + } + + let paste = "app frame after Paste Into on 24 MP (CPU canvas)"; + if b.wanted(paste) { + let (w, h) = sz.big_photo; + paste_into_frame_scenario(b, paste, w, h); + } +} + +/// #9329 PR C: the whole app (kittest harness, CPU canvas) with a 24 MP photo. Each sample runs +/// Paste Into a 5 % selection (untimed, after a frame that shows the selection), then times the +/// next frame, then undoes the paste and the selection (untimed). Paste Into is a compound command (several +/// revisions), so the frame's refresh goes through the real `damage_since` path. +fn paste_into_frame_scenario(b: &mut Bench, name: &str, w: u32, h: u32) { + // 0.224² ≈ 5 % of the canvas. + let sel = json!({"x": w / 2, "y": h / 2, "width": w * 224 / 1000, "height": h * 224 / 1000}); + let built = open_photo(w, h).and_then(|mut s| { + exec(&mut s, "select.rect", json!({"x": w / 10, "y": h / 10, "width": w / 5, "height": h / 5}))?; + exec(&mut s, "edit.copy", json!({}))?; + Ok(s) + }); + let mut s = match built { + Ok(s) => s, + Err(e) => return b.errors.push((name.into(), e)), + }; + let doc = std::mem::take(&mut s); + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(4).build_eframe(move |cc| { + photocraft_ui_egui::PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + photocraft_ui_egui::PhotocraftApp::new(doc, photocraft_ui_egui::Services::default()) + }); + // Warm up: first frames build the canvas cache of the 24 MP document. + harness.run_steps(6); + b.current = Some(name.to_string()); + b.sampler.reset(); + b.px.borrow_mut().clear(); + let mut samples = Vec::new(); + let run = (|| -> Res<()> { + let layers = |h: &egui_kittest::Harness<'_, photocraft_ui_egui::PhotocraftApp>| h.state().session.active().map(|d| d.doc.layers.len()); + let base_layers = layers(&harness); + let past = |h: &egui_kittest::Harness<'_, photocraft_ui_egui::PhotocraftApp>| h.state().session.active().map(|d| d.history.past_len()); + let base_past = past(&harness); + for i in 0..=b.reps.max(1) { + let rev = |h: &egui_kittest::Harness<'_, photocraft_ui_egui::PhotocraftApp>| h.state().session.active().map(|d| d.revision); + // Untimed: Paste Into turns the selection into the pasted layer's + // mask, so each sample re-creates the same ~5 % selection (the + // clipboard is not consumed), and shows it for a frame, as the app + // does between a selection and the next command. Without that frame + // the canvas would last have shown the revision before `select.rect`, + // two commands back, and redraw everything whatever Paste Into reports. + harness.state_mut().run("select.rect", sel.clone())?; + harness.step(); + let before = rev(&harness).ok_or("no document")?; + harness.state_mut().run("edit.pasteSpecial.pasteInto", json!({}))?; + let after = rev(&harness).ok_or("no document")?; + // The path claim: a multi-revision command. + if after < before + 2 { + return Err(format!("path check: Paste Into moved revision by {}, not >= 2", after - before)); + } + harness.state_mut().perf.last_refresh_px = 0; + let t = Instant::now(); + harness.step(); + let took = ms(t); + let px = harness.state().perf.last_refresh_px; + if px == 0 { + return Err("path check: the frame after Paste Into recorded no refresh".into()); + } + // Untimed: undo the paste and then the selection (one history step each), so every + // sample pastes onto the same document rather than onto the layers earlier samples + // pasted, and starts from the same history rather than one more selection state per + // sample. The next sample's selection frame shows the undone document before its timer. + harness.state_mut().run("edit.undo", json!({}))?; + if layers(&harness) != base_layers { + return Err("path check: undoing Paste Into did not restore the layer stack".into()); + } + harness.state_mut().run("edit.undo", json!({}))?; + if past(&harness) != base_past { + return Err("path check: undoing Paste Into and the selection did not restore the history".into()); + } + // Sample 0 is the warm-up. + if i > 0 { + samples.push(took); + b.px.borrow_mut().push(px); + } + } + Ok(()) + })(); + // The rows' document handle: the harness's session. + let st = std::mem::take(&mut harness.state_mut().session); + b.record(name, &st, &samples, &[], run); } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 834bcfc5dd..472f0289fe 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -99,6 +99,7 @@ impl PhotocraftApp { fonts_ready: false, last_canvas_rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)), arrange_start: 0, + drawing_window: None, ppp: 1.0, drop_canvas_rect: None, tab_strip: None, @@ -159,6 +160,8 @@ impl PhotocraftApp { clip_read_for_paste: false, smart_svg: Default::default(), transform_preview: None, + transform_area: None, + transform_preparing: None, move_mods: Default::default(), nudge_bundle: Default::default(), style_preview: None, diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 1032873c56..ab20ffca36 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -8,13 +8,19 @@ impl PhotocraftApp { } /// Close this frame's stage record (`frame_stages`): keep it if it was slow, and hand it to - /// the stroke trace. `ui_ms` is the UI build's time. - pub(crate) fn finish_frame(&mut self, ui_ms: f64) { - let mut stages = std::mem::take(&mut self.perf.stage); - stages.ui_ms = ui_ms; + /// the stroke trace. `ui_ms` is this pass's UI build. A pass egui will run again + /// (`request_discard`, such as a sizing pass) leaves the record open, so a frame is one + /// record across all its passes. + pub(crate) fn finish_frame(&mut self, ctx: &egui::Context, ui_ms: f64) { + self.perf.stage.ui_ms += ui_ms; + self.perf.stage.stroking |= self.live_stroke.is_some(); + if ctx.will_discard() { + return; + } + let stages = std::mem::take(&mut self.perf.stage); let stages = self.slow_frames.finish(stages, gpu_canvas::now_ms(), self.perf.gpu, self.perf.gpu_ms); let info = &self.perf.gpu_info; - self.stroke_trace.frame(&stages, self.live_stroke.is_some(), || { + self.stroke_trace.frame(&stages, stages.stroking, || { let gpu = format!("{} {}", info.backend, info.adapter).trim().to_string(); if info.present.is_empty() { gpu } else { format!("{gpu}, {}", info.present) } }); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 26ac96f722..8264895665 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -137,6 +137,7 @@ impl PhotocraftApp { order, question, policy_applied: false, + smart_object: false, }, ); Ok(warnings) diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index dafe8a25ef..04d63960e1 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -75,6 +75,7 @@ impl PhotocraftApp { vector_ui::finish_pen_if_left(self); transform_tool::end_if_left(self); shape_stroke_ui::sync_editor(self, ctx); + crate::dock::persist_pending(self, ctx); prefs_ui::tick(self, ctx); updates_ui::tick(self, ctx); monitor_status::poll_frame(self, ctx, frame); @@ -182,7 +183,7 @@ impl PhotocraftApp { // No editor was drawn this pass: end its IME context rather than keep a stale owner. type_tool::sync_ime(self, &ctx); // The frame's stage record was started with its input: close it here too. - self.finish_frame(0.0); + self.finish_frame(&ctx, 0.0); return; } let t0 = gpu_canvas::now_ms(); @@ -205,7 +206,7 @@ impl PhotocraftApp { self.perf.record_gpu(t); } self.perf.frame(ui_ms); - self.finish_frame(ui_ms); + self.finish_frame(&ctx, ui_ms); if !drawn { return; } @@ -300,21 +301,44 @@ impl PhotocraftApp { if chrome && self.ui.panels.status_bar && !home { panels::status_bar(self, ui); } - if ((chrome && self.ui.panels.toolbar) || tabbed_in) && !home { - panels::toolbar(self, ui); - } + let toolbar_shown = ((chrome && self.ui.panels.toolbar) || tabbed_in) && !home; // craft-ui's layout holds the canvas as its protected `canvas` panel. let docking = ((chrome && self.ui.panels.dock) || tabbed_in) && !home; - if docking { - panels::dock_area(self, ui); - } else { + let toolbar_side = self.ui.panels.toolbar_side.resolve(); + let toolbar_right = toolbar_side == crate::state::ToolbarSide::Right; + // The compact layout stacks the dock, rail and toolbar on the dock's physical edge. + let dock_right = !crate::direction::is_rtl(); + let toolbar_at_dock_edge = toolbar_right == dock_right; + // The dock-edge layout drops the canvas from craft-ui's split, which is only safe while + // nothing else is docked beside it. A panel already beside the canvas keeps the standard + // layout so it stays visible and dockable. The layout must not change once a drag starts: + // craft-ui records the areas on the press, and swapping the shape cancels the drag. + let dock_edge_layout = toolbar_shown && docking && toolbar_at_dock_edge && crate::panel_docking::canvas_alone(self); + if dock_edge_layout { + // Dock outermost, then its rail, then the toolbox, then the canvas: the toolbox sits + // between the canvas and the dock, not outside the dock at the window edge. + panels::dock_panel(self, ui); + panels::toolbar(self, ui); let t = theme::Tokens::get(&ctx); let backdrop = if chrome { prefs_ui::pasteboard_color(self).unwrap_or(t.canvas) } else { egui::Color32::BLACK }; egui::CentralPanel::default().frame(egui::Frame::NONE.fill(backdrop)).show(ui, |ui| { canvas::document_area(self, ui); }); - if !home { - panels::properties_window(self, &ctx); + } else { + if toolbar_shown { + panels::toolbar(self, ui); + } + if docking { + panels::dock_area(self, ui); + } else { + let t = theme::Tokens::get(&ctx); + let backdrop = if chrome { prefs_ui::pasteboard_color(self).unwrap_or(t.canvas) } else { egui::Color32::BLACK }; + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(backdrop)).show(ui, |ui| { + canvas::document_area(self, ui); + }); + if !home { + panels::properties_window(self, &ctx); + } } } // The floating editor windows belong to the editor: Home covers them (dialogs and notices diff --git a/crates/ui-egui/src/background_eraser_bar_angle_tests.rs b/crates/ui-egui/src/background_eraser_bar_angle_tests.rs new file mode 100644 index 0000000000..2d897fe01f --- /dev/null +++ b/crates/ui-egui/src/background_eraser_bar_angle_tests.rs @@ -0,0 +1,274 @@ +//! #11908: the Background Eraser's options bar has an Angle field between Tolerance and Protect +//! Foreground Color (0° by default, "Set the brush angle", whole degrees from −180 to 180, with the +//! reference application's alert for a typed value outside that) and a Pressure for Size toggle +//! after Protect Foreground Color. Both edit the tool's own brush. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; +use crate::theme::ThemeKind; + +const PRESSURE: &str = "Always use pressure for size"; + +fn bar(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + let mut h = Harness::builder().with_size(vec2(1600.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, ThemeKind::ProMedium); + h.run_steps(4); + h +} + +fn angle_field<'a>(h: &'a Harness<'static, PhotocraftApp>) -> Option> { + h.query_all_by_role(egui::accesskit::Role::SpinButton).find(|n| n.accesskit_node().description().as_deref() == Some("Set the brush angle")) +} + +fn shown(h: &Harness<'static, PhotocraftApp>) -> String { + angle_field(h).expect("the Angle field").accesskit_node().value().map(|v| v.to_string()).unwrap_or_default() +} + +fn left(h: &Harness<'static, PhotocraftApp>, label: &str) -> f64 { + h.get_by_label(label).accesskit_node().bounding_box().expect(label).x0 +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + let dialogs = &h.state().ui.dialogs; + dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +fn type_angle(h: &mut Harness<'static, PhotocraftApp>, text: &str) -> f32 { + angle_field(h).expect("the Angle field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); + h.state().session.tools.brush.angle +} + +#[test] +fn angle_sits_between_tolerance_and_protect_foreground_color() { + let h = bar(Tool::BackgroundEraser); + let field = angle_field(&h).expect("the Angle field"); + let angle = field.accesskit_node().bounding_box().unwrap().x0; + assert!(shown(&h).starts_with('0'), "default 0°: {}", shown(&h)); + assert!(left(&h, "Tolerance:") < angle && angle < left(&h, "Protect Foreground Color"), "Tolerance < Angle < Protect Foreground Color"); + assert_eq!(h.state().session.tools.brush.angle, 0.0); +} + +#[test] +fn typed_angles_are_whole_degrees_clamped_with_the_alert() { + let mut h = bar(Tool::BackgroundEraser); + assert_eq!(type_angle(&mut h, "45.5"), 45.0); + assert_eq!(type_angle(&mut h, "-30"), -30.0); + assert!(alerts(&h).is_empty(), "in range: no alert, {:?}", alerts(&h)); + assert_eq!(type_angle(&mut h, "400"), 180.0); + assert_eq!(alerts(&h), vec!["An integer between -180 ° and 180 ° is required. Closest value inserted.".to_string()]); + assert!(shown(&h).starts_with("180"), "{}", shown(&h)); + h.state_mut().ui.dialogs.clear(); + assert_eq!(type_angle(&mut h, "-200"), -180.0); + assert_eq!(alerts(&h).len(), 1, "one alert for -200"); +} + +#[test] +fn an_entry_left_by_a_tool_switch_does_not_alert_later() { + let mut h = bar(Tool::BackgroundEraser); + angle_field(&h).expect("the Angle field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("400".into())); + h.run_steps(1); + // The tool changes before the entry is committed: the field goes away mid-typing. + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(3); + h.state_mut().ui.tool = Tool::BackgroundEraser; + h.run_steps(3); + angle_field(&h).expect("the Angle field").click(); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(alerts(&h).is_empty(), "nothing typed this time: {:?}", alerts(&h)); +} + +#[test] +fn an_entry_kept_while_the_window_is_in_the_background_still_alerts() { + let mut h = bar(Tool::BackgroundEraser); + angle_field(&h).expect("the Angle field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("400".into())); + h.run_steps(1); + // Another window takes the focus mid-entry, then this one gets it back. + h.input_mut().focused = false; + h.event(egui::Event::WindowFocused(false)); + h.run_steps(3); + h.input_mut().focused = true; + h.event(egui::Event::WindowFocused(true)); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(h.state().session.tools.brush.angle, 180.0); + assert_eq!(alerts(&h), vec![crate::eraser_ui::ANGLE_RANGE_MESSAGE.to_string()], "typed before the switch, so it alerts"); +} + +#[test] +fn pressure_for_size_follows_protect_foreground_color_off_by_default() { + let mut h = bar(Tool::BackgroundEraser); + assert!(left(&h, "Protect Foreground Color") < left(&h, PRESSURE)); + assert!(!h.state().session.tools.brush.pressure_size, "off by default"); + h.get_by_label(PRESSURE).click(); + h.run_steps(2); + assert!(h.state().session.tools.brush.pressure_size); + h.get_by_label(PRESSURE).click(); + h.run_steps(2); + assert!(!h.state().session.tools.brush.pressure_size); +} + +#[test] +fn angle_and_pressure_are_the_background_erasers_own() { + let mut h = bar(Tool::Brush); + h.state_mut().run("tools.setBrush", json!({"brush": {"angle": -20.0}})).unwrap(); + h.run_steps(2); + h.state_mut().ui.tool = Tool::BackgroundEraser; + h.run_steps(3); + type_angle(&mut h, "30"); + h.get_by_label(PRESSURE).click(); + h.run_steps(2); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(3); + let brush = &h.state().session.tools.brush; + assert_eq!((brush.angle, brush.pressure_size), (-20.0, false), "the Brush keeps its own angle and pressure"); + h.state_mut().ui.tool = Tool::BackgroundEraser; + h.run_steps(3); + let brush = &h.state().session.tools.brush; + assert_eq!((brush.angle, brush.pressure_size), (30.0, true), "the Background Eraser's values come back"); + assert!(shown(&h).starts_with("30"), "{}", shown(&h)); +} + +#[test] +fn the_field_shows_the_brush_settings_angle() { + let mut h = bar(Tool::BackgroundEraser); + // The Brush Settings panel edits the live brush's angle through `tools.setBrush`. + h.state_mut().run("tools.setBrush", json!({"brush": {"angle": 60.0}})).unwrap(); + h.run_steps(2); + assert!(shown(&h).starts_with("60"), "{}", shown(&h)); + type_angle(&mut h, "-75"); + assert_eq!(h.state().session.tools.brush.angle, -75.0, "what the panel reads"); +} + +#[test] +fn the_magic_eraser_has_neither() { + let bg = bar(Tool::BackgroundEraser); + assert!(bg.query_by_label("Angle").is_some(), "the Background Eraser's field is found by its name"); + let h = bar(Tool::MagicEraser); + assert!(angle_field(&h).is_none()); + assert!(h.query_by_label("Angle").is_none(), "no field named Angle, whatever its tooltip"); + assert!(h.query_by_label(PRESSURE).is_none()); +} + +/// Focus the field and press `key` `n` times, then Enter. +fn step_angle(h: &mut Harness<'static, PhotocraftApp>, key: egui::Key, n: usize) -> f32 { + angle_field(h).expect("the Angle field").click(); + h.run_steps(1); + for _ in 0..n { + h.key_press(key); + h.run_steps(1); + } + h.key_press(egui::Key::Enter); + h.run_steps(2); + h.state().session.tools.brush.angle +} + +#[test] +fn arrow_steps_stop_at_the_ends_without_the_alert() { + let mut h = bar(Tool::BackgroundEraser); + type_angle(&mut h, "178"); + assert_eq!(step_angle(&mut h, egui::Key::ArrowUp, 5), 180.0); + type_angle(&mut h, "-178"); + assert_eq!(step_angle(&mut h, egui::Key::ArrowDown, 5), -180.0); + assert!(alerts(&h).is_empty(), "stepping is not typing: {:?}", alerts(&h)); +} + +#[test] +fn a_click_away_commits_with_the_alert() { + let mut h = bar(Tool::BackgroundEraser); + angle_field(&h).expect("the Angle field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("400".into())); + h.run_steps(1); + h.get_by_label(PRESSURE).click(); + h.run_steps(3); + assert_eq!(h.state().session.tools.brush.angle, 180.0); + assert_eq!(alerts(&h).len(), 1, "one alert on click-away: {:?}", alerts(&h)); +} + +#[test] +fn an_entry_that_is_not_a_number_keeps_the_angle_without_the_alert() { + let mut h = bar(Tool::BackgroundEraser); + type_angle(&mut h, "30"); + for text in ["", "abc", "inf", "NaN"] { + assert_eq!(type_angle(&mut h, text), 30.0, "{text:?}"); + } + assert!(alerts(&h).is_empty(), "{:?}", alerts(&h)); +} + +fn wheel_event(lines: f32) -> egui::Event { + egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, lines), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + } +} + +#[test] +fn wheel_steps_with_the_focus_stop_at_the_ends_without_the_alert() { + // As in the app: the focused field takes the wheel before the bar is laid out. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = Tool::BackgroundEraser; + let mut h = Harness::builder().with_size(vec2(1600.0, 300.0)).build_ui_state( + |ui, app| { + crate::field_wheel::begin_frame(ui.ctx()); + crate::panels::options_bar(app, ui) + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, ThemeKind::ProMedium); + h.run_steps(4); + type_angle(&mut h, "178"); + angle_field(&h).expect("the Angle field").click(); + h.run_steps(1); + for _ in 0..5 { + h.event(wheel_event(1.0)); + h.run_steps(1); + } + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(h.state().session.tools.brush.angle, 180.0); + assert!(alerts(&h).is_empty(), "a wheel step is not typing: {:?}", alerts(&h)); +} + +#[test] +fn a_view_scroll_while_typing_keeps_the_alert() { + let mut h = bar(Tool::BackgroundEraser); + angle_field(&h).expect("the Angle field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + // A scroll the field does not take (no wheel hand-off here) arrives with the typed text. + h.event(wheel_event(-3.0)); + h.event(egui::Event::Text("400".into())); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(h.state().session.tools.brush.angle, 180.0); + assert_eq!(alerts(&h), vec![crate::eraser_ui::ANGLE_RANGE_MESSAGE.to_string()], "typed, so it alerts"); +} diff --git a/crates/ui-egui/src/background_eraser_brush_popup_tests.rs b/crates/ui-egui/src/background_eraser_brush_popup_tests.rs new file mode 100644 index 0000000000..3c0dbd2b54 --- /dev/null +++ b/crates/ui-egui/src/background_eraser_brush_popup_tests.rs @@ -0,0 +1,138 @@ +//! #11910: with the Background Eraser, the options-bar brush picker and a canvas right-click open +//! a compact popup (Size, Hardness, Spacing, the angle/roundness widget, Angle, Roundness, the +//! "Size:" and "Tolerance:" pen dropdowns with the tablet warning) and no preset list; other tools +//! keep the Brush Preset picker. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::*; +use crate::PhotocraftApp; +use crate::state::Tool; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + app.ui.tool = tool; + app.sync_views(); + app +} + +/// The canvas with the picker open as the brush chip opens it. +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::paint_mouse::sync_tool_brush(app); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h +} + +fn open(h: &mut Harness<'static, PhotocraftApp>) { + let c = h.state().last_canvas_rect.center(); + let ctx = h.ctx.clone(); + crate::brush_picker::open(&mut h.state_mut().ui, &ctx, [c.x, c.y]); + h.run_steps(3); +} + +fn top(h: &Harness<'static, PhotocraftApp>, label: &str) -> f32 { + h.get_by_label(label).rect().top() +} + +#[test] +fn the_popup_has_the_controls_in_order_and_no_presets() { + let mut h = harness(app(Tool::BackgroundEraser)); + open(&mut h); + let order = ["Size", "Hardness", "Spacing", "Angle", "Roundness", "Size:", "Tolerance:"]; + let tops: Vec = order + .iter() + .map(|l| match *l { + // The Size field, the dropdowns by their combo boxes. + "Size" => h.get_all_by_role(Role::SpinButton).next().expect("the Size field").rect().top(), + "Size:" | "Tolerance:" => h.get_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().label().as_deref() == Some(*l)).expect(l).rect().top(), + "Hardness" | "Spacing" => h.query_all_by_label(l).next().expect(l).rect().top(), + _ => top(&h, l), + }) + .collect(); + assert!(tops.windows(2).all(|w| w[0] <= w[1]), "top to bottom {order:?}: {tops:?}"); + assert!(h.query_by_label(PRESSURE_WARNING).is_some(), "the warning triangle beside Tolerance:"); + assert!(h.query_by_label("Search Brushes").is_none() && h.query_by_label("Brush Preset Options").is_none(), "no presets, search or gear"); +} + +#[test] +fn the_defaults_are_the_references() { + let app = app(Tool::BackgroundEraser); + assert_eq!(app.ui.tool_options.bg_tolerance_control, PEN_PRESSURE, "Tolerance: Pen Pressure by default"); + assert_eq!(size_control(&app.session.tools.brush), OFF, "Size: Off"); + let mut h = harness(app); + open(&mut h); + let value = |l: &str| { + h.get_all_by_role(Role::ComboBox) + .find(|n| n.accesskit_node().label().as_deref() == Some(l)) + .and_then(|n| n.accesskit_node().value()) + .unwrap_or_default() + }; + assert_eq!(value("Size:"), "Off"); + assert_eq!(value("Tolerance:"), "Pen Pressure"); +} + +#[test] +fn tolerance_is_stored_with_the_tool_and_size_with_its_brush() { + let mut h = harness(app(Tool::BackgroundEraser)); + open(&mut h); + h.get_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().label().as_deref() == Some("Tolerance:")).unwrap().click(); + h.run_steps(2); + h.get_all_by_label("Off").last().expect("the Off entry").click(); + h.run_steps(3); + assert_eq!(h.state().ui.tool_options.bg_tolerance_control, OFF); + h.get_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().label().as_deref() == Some("Size:")).unwrap().click(); + h.run_steps(2); + h.get_all_by_label("Pen Pressure").last().expect("the Pen Pressure entry").click(); + h.run_steps(3); + assert!(h.state().session.tools.brush.pressure_size, "Size: Pen Pressure is the brush's pressure for size"); + // The mapping both ways. + let mut b = BrushSettings::default(); + for c in [STYLUS_WHEEL, PEN_PRESSURE, OFF] { + set_size_control(&mut b, c); + assert_eq!(size_control(&b), c); + } +} + +#[test] +fn escape_closes_and_a_right_click_erases_nothing() { + let mut h = harness(app(Tool::BackgroundEraser)); + let steps = h.state().session.active().unwrap().history.past_len(); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); + } + assert!(h.state().ui.brush_picker.is_some(), "the right-click opens the popup"); + assert!(h.query_all_by_label("Tolerance:").next().is_some(), "the compact popup, not the preset picker"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps, "nothing erased"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert_eq!(h.state().ui.brush_picker, None); +} + +#[test] +fn other_tools_keep_the_brush_preset_picker() { + let mut h = harness(app(Tool::Brush)); + open(&mut h); + assert!(h.query_by_label("Brush Preset Options").is_some(), "the Brush's picker with its gear"); + assert!(h.query_by_label(PRESSURE_WARNING).is_none()); +} diff --git a/crates/ui-egui/src/blend_dropdown_wheel_tests.rs b/crates/ui-egui/src/blend_dropdown_wheel_tests.rs index f3f69cdd45..6263f06bd8 100644 --- a/crates/ui-egui/src/blend_dropdown_wheel_tests.rs +++ b/crates/ui-egui/src/blend_dropdown_wheel_tests.rs @@ -166,16 +166,17 @@ fn wheel_steps_in_the_open_list_keep_the_chosen_mode_in_view() { let mut h = harness(pixel_layer); let at = dropdown(&h).center(); click(&mut h, at); - // Unscrolled, the list shows its first entry at the top and is at most 420 pt tall. - let (top, darken) = (entry(&h, "Normal").top(), entry(&h, "Darken").center()); + // The open list, unscrolled, shows its first entry at the top. + let list = h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))).unwrap(); + let darken = entry(&h, "Darken").center(); for _ in 0..22 { wheel(&mut h, darken, -1.0); } h.run_steps(30); assert_eq!(blend(&h), BlendMode::Divide); - let in_view = |r: Rect| r.top() >= top - 0.5 && r.bottom() <= top + 420.0 + 0.5; + let in_view = |r: Rect| list.contains_rect(r); let chosen = entry(&h, "Divide"); - assert!(in_view(chosen), "{chosen:?} in view below {top}"); + assert!(in_view(chosen), "{chosen:?} in view in {list:?}"); // The wheel over the button scrolls the open list along too. for _ in 0..21 { wheel(&mut h, at, 1.0); @@ -183,7 +184,7 @@ fn wheel_steps_in_the_open_list_keep_the_chosen_mode_in_view() { h.run_steps(30); assert_eq!(blend(&h), BlendMode::Dissolve); let chosen = entry(&h, "Dissolve"); - assert!(in_view(chosen), "{chosen:?} in view below {top}"); + assert!(in_view(chosen), "{chosen:?} in view in {list:?}"); } /// The mode the canvas previews on the active layer, if any (#970). @@ -212,3 +213,32 @@ fn a_wheel_step_ends_the_hover_preview_until_the_pointer_moves() { h.run_steps(3); assert_eq!(previewed(&mut h), Some(BlendMode::Multiply), "a moved pointer previews again"); } + +/// The open list's rect (the one foreground area: no other popup is open). +fn open_list(h: &Harness<'_, PhotocraftApp>) -> Option { + h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))) +} + +/// A plain click on the Layers panel's Blend Mode box, released where it was pressed (after one +/// frame, or after a few as a person's click takes), opens the list beside the box and chooses +/// nothing (#5495 review): the full-height list doesn't fit below the box low in the panel, and +/// it must not open over the box, where the release would pick the row under the pointer. +#[test] +fn a_click_on_the_blend_mode_box_opens_the_list_beside_it_and_changes_nothing() { + for held in [6, 1] { + let mut h = harness(pixel_layer); + let undo = steps(&h); + let button = dropdown(&h); + let at = button.center(); + h.hover_at(at); + h.run_steps(1); + for (pressed, frames) in [(true, held), (false, 4)] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.run_steps(frames); + } + assert_eq!((blend(&h), steps(&h)), (BlendMode::Normal, undo), "held {held}: the click chose nothing"); + let Some(list) = open_list(&h) else { panic!("held {held}: the list is open") }; + assert!(!list.intersects(button.shrink(1.0)), "held {held}: the list {list:?} leaves the box {button:?} free"); + assert!(list.top() >= 0.0 && list.bottom() <= 900.0, "held {held}: the list {list:?} is in the window"); + } +} diff --git a/crates/ui-egui/src/brush_blend_keys_behind_tests.rs b/crates/ui-egui/src/brush_blend_keys_behind_tests.rs new file mode 100644 index 0000000000..372bd5aca9 --- /dev/null +++ b/crates/ui-egui/src/brush_blend_keys_behind_tests.rs @@ -0,0 +1,122 @@ +//! #11896: Behind is one of the painting modes, so after Behind a Shift+Alt letter or a +//! Shift+minus/plus step that sets another mode leaves Behind, in the same one `tools.setBrush`. +//! With Behind off the keys work as before. + +use egui::{Key, Modifiers}; +use serde_json::{Value, json}; + +use super::*; + +const SHIFT_ALT: Modifiers = Modifiers { alt: true, ctrl: false, shift: true, mac_cmd: false, command: false }; + +/// A 64 × 64 document with a layer filled 220,30,30, black foreground, the Brush. +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#000000"})).unwrap(); + app.ui.tool = tool; + app +} + +/// One key press with `modifiers` through the app's shortcut handling. +fn key(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, modifiers: Modifiers) { + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn brush(app: &mut PhotocraftApp) -> Value { + app.run("brush.get", json!({})).unwrap() +} + +fn behind_on(app: &mut PhotocraftApp, ctx: &egui::Context) { + key(app, ctx, Key::Q, SHIFT_ALT); + assert_eq!(brush(app)["behind"], true, "Shift+Alt+Q turns Behind on"); +} + +fn journal(app: &PhotocraftApp) -> usize { + app.session.journal.len() +} + +/// The layer's pixel at (x, y) as 8-bit RGB. +fn pixel(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] { + let st = app.session.active().unwrap(); + let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8) +} + +#[test] +fn shift_alt_m_after_behind_multiplies_over_the_pixels() { + let ctx = egui::Context::default(); + let mut app = app(Tool::Brush); + behind_on(&mut app, &ctx); + let n = journal(&app); + key(&mut app, &ctx, Key::M, SHIFT_ALT); + let b = brush(&mut app); + assert_eq!((b["behind"].clone(), b["mode"].clone()), (json!(false), json!("Multiply")), "{b}"); + assert_eq!(journal(&app), n + 1, "one tools.setBrush"); + // A black stroke across the red layer multiplies it to black, not only under transparency. + app.run("paint.stroke", json!({"points": [[4, 32], [60, 32]], "size": 9, "hardness": 100})).unwrap(); + assert_eq!(pixel(&app, 32, 32), [0, 0, 0]); +} + +#[test] +fn shift_alt_n_l_and_r_after_behind_leave_it() { + let ctx = egui::Context::default(); + for (letter, mode) in [(Key::N, "Normal"), (Key::L, "HardMix")] { + let mut app = app(Tool::Brush); + behind_on(&mut app, &ctx); + let n = journal(&app); + key(&mut app, &ctx, letter, SHIFT_ALT); + let b = brush(&mut app); + assert_eq!(b["behind"], false, "{letter:?}: {b}"); + assert_eq!(b["mode"], json!(mode), "{letter:?}: {b}"); + assert_eq!(journal(&app), n + 1, "{letter:?}: one tools.setBrush"); + } + // Clear: Behind off and Clear on. + let mut app = app(Tool::Brush); + behind_on(&mut app, &ctx); + let n = journal(&app); + key(&mut app, &ctx, Key::R, SHIFT_ALT); + assert_eq!(brush(&mut app)["behind"], false); + assert!(app.ui.tool_options.brush_clear, "Clear on"); + assert_eq!(journal(&app), n + 1, "one tools.setBrush"); + // The Pencil too. + let mut app = self::app(Tool::Pencil); + behind_on(&mut app, &ctx); + key(&mut app, &ctx, Key::M, SHIFT_ALT); + assert_eq!(brush(&mut app)["behind"], false); +} + +#[test] +fn a_shift_step_after_behind_leaves_it() { + let ctx = egui::Context::default(); + for step in [Key::Minus, Key::Plus] { + let mut app = app(Tool::Brush); + behind_on(&mut app, &ctx); + let n = journal(&app); + key(&mut app, &ctx, step, Modifiers::SHIFT); + assert_eq!(brush(&mut app)["behind"], false, "{step:?}"); + assert_eq!(journal(&app), n + 1, "{step:?}: one tools.setBrush"); + } +} + +#[test] +fn with_behind_off_the_keys_send_what_they_did() { + let ctx = egui::Context::default(); + let mut app = app(Tool::Brush); + key(&mut app, &ctx, Key::M, SHIFT_ALT); + let (id, params) = app.session.journal.last().cloned().unwrap(); + assert_eq!((id.as_str(), params), ("tools.setBrush", json!({"brush": {"mode": "Multiply"}})), "only the mode, as before"); + // Clear with Behind off sends nothing, as before (Clear is the options' flag). + let n = journal(&app); + key(&mut app, &ctx, Key::R, SHIFT_ALT); + assert_eq!(journal(&app), n); + assert!(app.ui.tool_options.brush_clear); +} diff --git a/crates/ui-egui/src/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs index 431ad7aea2..71259e9f53 100644 --- a/crates/ui-egui/src/brush_mode_menu.rs +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -166,6 +166,17 @@ pub(crate) fn is_gesture(tool: Tool, mods: egui::Modifiers) -> bool { mods.shift && !mods.alt && !mods.ctrl && !mods.command && !mods.mac_cmd && !items(tool).is_empty() } +/// Does a right-click with `mods` open the menu? The Shift gesture for every tool that has one, +/// and a plain right-click with the Eraser in Block mode, where the Brush Preset picker's Size and +/// Hardness mean nothing (#11937, as in the reference application). +/// A plain right-click opens it only where it would otherwise open the picker: with the Erase +/// preference it still erases. +pub(crate) fn opens_on(app: &PhotocraftApp, tool: Tool, mods: egui::Modifiers) -> bool { + let plain = !mods.shift && !mods.alt && !mods.ctrl && !mods.command && !mods.mac_cmd; + let block = tool == Tool::Eraser && app.ui.tool_options.eraser_mode == "block"; + is_gesture(tool, mods) || (plain && block && !crate::paint_mouse::right_erases(app, tool)) +} + /// The modifiers that decide a right-button gesture: the ones held when the button went down. /// egui reports `secondary_clicked` on release, so letting go of Shift a moment before the button /// must not turn Shift+right-click into a plain right-click (an erase dab, with the Erase @@ -382,3 +393,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &Context) { close(app); } } + +#[cfg(test)] +#[path = "eraser_block_right_click_tests.rs"] +mod eraser_block_right_click_tests; diff --git a/crates/ui-egui/src/brush_picker_angle_widget_tests.rs b/crates/ui-egui/src/brush_picker_angle_widget_tests.rs new file mode 100644 index 0000000000..caed875a5b --- /dev/null +++ b/crates/ui-egui/src/brush_picker_angle_widget_tests.rs @@ -0,0 +1,167 @@ +//! #11821: the Brush Preset picker shows the tip's angle/roundness widget at its top left, the +//! Brush Settings panel's own widget, and its drags go through `tools.setBrush` as one journaled +//! change each; Escape reverts them as it does a Size or Hardness edit. + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::brush_sections::{EllipseGrab, ellipse_drag, ellipse_grab, roundness_handles}; +use crate::state::Tool; + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 1.0, "angle": 0.0, "roundness": 1.0}})).unwrap(); + app.ui.tool = Tool::Brush; + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let c = h.state().last_canvas_rect.center(); + let ctx = h.ctx.clone(); + crate::brush_picker::open(&mut h.state_mut().ui, &ctx, [c.x, c.y]); + h.run_steps(3); + h +} + +/// The widget's centre on screen. It is the top block's first item, 84 × 84, and the Size column +/// starts one item spacing right of it, its first row (24 pt tall, the label centred in it) level +/// with the widget's top. +fn widget_centre(h: &Harness<'static, PhotocraftApp>) -> Pos2 { + use egui_kittest::kittest::Queryable; + let picker = h.ctx.memory(|m| m.area_rect(crate::brush_picker::picker_id())).expect("the picker is open"); + let label = h.query_all_by_label(crate::i18n::t("Size")).find(|n| picker.contains(n.rect().center())).expect("the picker's Size label").rect(); + let spacing = h.ctx.global_style().spacing.item_spacing.x; + Pos2::new(label.left() - spacing - 42.0, label.center().y - 12.0 + 42.0) +} + +fn brush(h: &Harness<'static, PhotocraftApp>) -> (f32, f32) { + let b = &h.state().session.tools.brush; + (b.angle, b.roundness) +} + +/// A press at `from`, moves through `path` and the release at its end, a frame each. +fn drag(h: &mut Harness<'static, PhotocraftApp>, from: Pos2, path: &[Pos2]) { + h.event(Event::PointerMoved(from)); + h.run_steps(1); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for p in path { + h.event(Event::PointerMoved(*p)); + h.run_steps(1); + } + let end = path.last().copied().unwrap_or(from); + h.event(Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +#[test] +fn the_widget_sits_at_the_pickers_top_left_left_of_size() { + use egui_kittest::kittest::Queryable; + let h = harness(); + let c = widget_centre(&h); + // Its top left is the picker's content corner: inside the popup frame's margin and stroke. + let picker = h.ctx.memory(|m| m.area_rect(crate::brush_picker::picker_id())).expect("the picker is open"); + let style = h.ctx.global_style(); + let inset = + vec2(f32::from(style.spacing.menu_margin.left), f32::from(style.spacing.menu_margin.top)) + egui::Vec2::splat(style.visuals.window_stroke().width); + let corner = c - vec2(42.0, 42.0); + assert!((corner - (picker.min + inset)).length() <= 2.0, "the widget at the top left: {corner:?} vs {:?}", picker.min + inset); + // The Size field is right of it, in the same top block. + let size = h.get_all_by_role(egui::accesskit::Role::SpinButton).next().expect("the Size field").rect(); + assert!(size.left() > c.x + 42.0 && size.top() < c.y + 42.0, "{size:?} vs centre {c:?}"); +} + +#[test] +fn dragging_the_arrow_sets_the_angle_as_the_panel_widget_does() { + let mut h = harness(); + let c = widget_centre(&h); + let (angle, roundness) = brush(&h); + // On the arrow (angle 0 points right), away from the roundness handles. + let from = c + vec2(28.0, 0.0); + assert_eq!(ellipse_grab(from - c, angle, roundness), EllipseGrab::Angle); + let to = c + vec2(-20.0, -20.0); + let journal = h.state().session.journal.len(); + drag(&mut h, from, &[c + vec2(10.0, -25.0), to]); + let want = ellipse_drag(EllipseGrab::Angle, to - c, angle, roundness); + assert_eq!(brush(&h), want, "the panel widget's values for the same drag"); + assert_eq!(want.0, 135.0); + let added: Vec = h.state().session.journal[journal..].iter().map(|(id, _)| id.clone()).collect(); + assert_eq!(added, ["tools.setBrush"], "one journaled change for the drag"); +} + +#[test] +fn dragging_a_handle_sets_the_roundness_as_the_panel_widget_does() { + let mut h = harness(); + let c = widget_centre(&h); + let (angle, roundness) = brush(&h); + let handle = c + roundness_handles(angle, roundness)[0]; + assert_eq!(ellipse_grab(handle - c, angle, roundness), EllipseGrab::Roundness); + let to = c + vec2(3.0, -12.0); + // The grab is judged where the drag starts: the first move stays within the handle's reach. + drag(&mut h, handle, &[handle + vec2(0.0, 6.5), c + vec2(2.0, -20.0), to]); + let want = ellipse_drag(EllipseGrab::Roundness, to - c, angle, roundness); + assert_eq!(brush(&h), want); + assert!((want.1 - 12.0 / 34.0).abs() < 1e-4, "{want:?}"); + // The Brush Settings panel reads the same brush. + assert_eq!(h.state().session.tools.brush.roundness, want.1); +} + +#[test] +fn escape_reverts_an_angle_edit_as_it_does_a_size_edit() { + let mut h = harness(); + let c = widget_centre(&h); + let opened = brush(&h); + drag(&mut h, c + vec2(28.0, 0.0), &[c + vec2(20.0, -15.0), c + vec2(0.0, -30.0)]); + assert_eq!(brush(&h).0, 90.0); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert_eq!(brush(&h), opened, "Escape goes back to the values the picker opened with"); + assert_eq!(h.state().ui.brush_picker, None, "and closes it"); +} + +#[test] +fn enter_keeps_an_angle_edit_and_closes() { + let mut h = harness(); + let c = widget_centre(&h); + drag(&mut h, c + vec2(28.0, 0.0), &[c + vec2(20.0, 15.0), c + vec2(0.0, 30.0)]); + assert_eq!(brush(&h).0, -90.0); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(brush(&h).0, -90.0); + assert_eq!(h.state().ui.brush_picker, None); +} + +#[test] +fn non_finite_pointer_positions_leave_the_brush_unchanged() { + let mut h = harness(); + let c = widget_centre(&h); + let before = brush(&h); + let handle = c + roundness_handles(before.0, before.1)[0]; + h.event(Event::PointerMoved(handle)); + h.run_steps(1); + h.event(Event::PointerButton { pos: handle, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + // The pointer reports non-finite positions while the handle is held. (egui's own debug checks + // panic once a drag is under way at such a position, or on a release there, so the test stops + // here.) + for p in [Pos2::new(f32::NAN, c.y), Pos2::new(c.x, f32::INFINITY)] { + h.event(Event::PointerMoved(p)); + h.run_steps(1); + let now = brush(&h); + assert!(now.0.is_finite() && now.1.is_finite(), "{p:?}: {now:?}"); + assert_eq!(now, before, "{p:?}"); + } +} diff --git a/crates/ui-egui/src/brush_picker_gear_menu_tests.rs b/crates/ui-egui/src/brush_picker_gear_menu_tests.rs new file mode 100644 index 0000000000..1c2b38161e --- /dev/null +++ b/crates/ui-egui/src/brush_picker_gear_menu_tests.rs @@ -0,0 +1,208 @@ +//! The Brush Preset picker's gear menu: Photoshop's entries in its order with its separators, the +//! picker's defaults (Brush Tip off, Show Search Bar on) and which entries are greyed (#11819). + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::*; +use crate::state::Tool; + +/// Photoshop's gear menu, measured top to bottom; "―" is a separator. +const MEASURED: &[&str] = &[ + "New Brush Preset…", + "New Brush Group…", + "―", + "Rename Brush…", + "Delete Brush…", + "―", + "Brush Name", + "Brush Stroke", + "Brush Tip", + "―", + "Show Additional Preset Info", + "―", + "Show Search Bar", + "Show Recent Brushes", + "―", + "Append Default Brushes…", + "Import Brushes…", + "Export Selected Brushes…", + "―", + "Get More Brushes…", + "―", + "Converted Legacy Tool Presets", + "Legacy Brushes", +]; + +/// The entries a click works on with a preset selected; every other one is greyed. +const LIVE: &[&str] = &["New Brush Preset…", "Rename Brush…", "Delete Brush…", "Brush Name", "Brush Stroke", "Brush Tip", "Show Search Bar", "Import Brushes…"]; + +/// The entries that act on the selected preset. +const NEEDS_PRESET: &[&str] = &["Rename Brush…", "Delete Brush…", "Export Selected Brushes…"]; + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::Brush; + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1200.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h +} + +/// [`harness`] with the first preset picked, as after a click on it. +fn harness_with_preset() -> Harness<'static, PhotocraftApp> { + let mut h = harness(); + let first = h.state().session.tools.presets.first().map(|p| p.name.clone()).expect("the default presets"); + h.state_mut().run("tools.setBrush", json!({ "preset": first })).unwrap(); + h.run_steps(2); + h +} + +/// Open the picker near the canvas's top left (room below for the whole menu), then its gear. +fn open_gear(h: &mut Harness<'static, PhotocraftApp>) { + let r = h.state().last_canvas_rect; + h.state_mut().ui.brush_picker = Some([r.left() + 20.0, r.top() + 10.0]); + h.run_steps(2); + h.get_by_label("Brush Preset Options").click(); + h.run_steps(2); +} + +fn entries() -> Vec<&'static str> { + GEAR_MENU.iter().filter_map(|e| e.map(Gear::label)).collect() +} + +#[test] +fn the_gear_menu_lists_the_reference_entries_in_order_with_its_separators() { + let menu: Vec<&str> = GEAR_MENU.iter().map(|e| e.map_or("―", Gear::label)).collect(); + assert_eq!(menu, MEASURED); + // The menu drawn: every entry once, top to bottom in that order. + let mut h = harness(); + open_gear(&mut h); + let tops: Vec = entries().iter().map(|l| h.get_by_label(l).rect().top()).collect(); + assert!(tops.windows(2).all(|w| w[0] < w[1]), "drawn top to bottom in the measured order: {tops:?}"); + assert!(h.query_all_by_label("Delete Brush").next().is_none(), "Delete Brush… has its ellipsis"); +} + +#[test] +fn the_picker_starts_without_the_brush_tip_and_with_the_search_bar() { + let h = harness(); + let st = &h.state().ui.brush_picker_list; + assert!(st.show_name && st.show_stroke && !st.show_tip, "Brush Name and Brush Stroke on, Brush Tip off"); + assert!(st.show_search, "Show Search Bar is on"); + // The Brushes panel keeps its own default. + assert!(h.state().ui.brushes_panel.show_tip); + // The menu shows the same, and the placeholders keep Photoshop's checks. + let mut h = harness(); + open_gear(&mut h); + for (label, on) in [ + ("Brush Name", true), + ("Brush Stroke", true), + ("Brush Tip", false), + ("Show Additional Preset Info", true), + ("Show Search Bar", true), + ("Show Recent Brushes", true), + ] { + let checked = h.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True); + assert_eq!(checked, on, "{label}"); + } +} + +#[test] +fn a_saved_brush_tip_still_wins_and_an_empty_card_gets_the_defaults_back() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.prefs.edit(|p| p.brush_picker = json!({"showTip": true, "showSearch": false})); + restore(&mut app); + assert!(app.ui.brush_picker_list.show_tip && !app.ui.brush_picker_list.show_search); + app.session.prefs.edit(|p| p.brush_picker = json!({"showName": false, "showStroke": false, "showTip": false})); + app.ui.brush_picker_list = list_state(); + restore(&mut app); + let st = &app.ui.brush_picker_list; + assert_eq!((st.show_name, st.show_stroke, st.show_tip), (true, true, false), "the at-least-one-part rule restores the defaults"); +} + +#[test] +fn show_search_bar_hides_the_search_field_and_is_remembered() { + let mut h = harness(); + open_gear(&mut h); + let fields = |h: &Harness<'static, PhotocraftApp>| h.query_all_by_role(Role::TextInput).count(); + let shown = fields(&h); + h.state_mut().ui.brush_picker_list.filter = "zzz".into(); + h.get_by_label("Show Search Bar").click(); + h.run_steps(3); + assert!(!h.state().ui.brush_picker_list.show_search); + assert_eq!(fields(&h), shown - 1, "the search field goes"); + assert!(h.state().ui.brush_picker_list.filter.is_empty(), "a hidden search filters nothing"); + let ctx = h.ctx.clone(); + persist(h.state_mut(), &ctx); + assert_eq!(h.state().session.prefs().brush_picker["showSearch"], json!(false)); + h.get_by_label("Show Search Bar").click(); + h.run_steps(3); + assert!(h.state().ui.brush_picker_list.show_search); + assert_eq!(fields(&h), shown, "and comes back"); +} + +#[test] +fn entries_without_a_function_and_preset_entries_without_a_preset_are_greyed() { + let mut h = harness_with_preset(); + open_gear(&mut h); + for label in entries() { + assert_eq!(!h.get_by_label(label).accesskit_node().is_disabled(), LIVE.contains(&label), "{label} with a preset selected"); + } + // A placeholder does nothing when clicked. + let before = (h.state().session.tools.presets.len(), h.state().ui.dialogs.len()); + h.get_by_label("New Brush Group…").click(); + h.run_steps(2); + assert_eq!((h.state().session.tools.presets.len(), h.state().ui.dialogs.len()), before); + // With no preset selected the preset's entries grey too. + let mut h = harness(); + assert!(h.state().session.tools.current_preset.is_none(), "a fresh session has no preset picked"); + open_gear(&mut h); + for label in entries() { + let live = LIVE.contains(&label) && !NEEDS_PRESET.contains(&label); + assert_eq!(!h.get_by_label(label).accesskit_node().is_disabled(), live, "{label} with no preset selected"); + } +} + +#[test] +fn delete_brush_still_deletes_the_selected_preset() { + let mut h = harness_with_preset(); + let name = h.state().session.tools.current_preset.clone().expect("a preset is selected"); + open_gear(&mut h); + h.get_by_label("Delete Brush…").click(); + h.run_steps(3); + assert!(!h.state().session.tools.presets.iter().any(|p| p.name == name), "{name} is deleted"); +} + +#[test] +fn two_clicks_in_one_frame_still_leave_one_card_part_on() { + let mut h = harness(); + open_gear(&mut h); + // Brush Tip is off; both remaining parts get an assistive-technology click in the same frame + // (kittest's own clicks each run a frame of their own, so the events go in by hand). + let clicks: Vec<_> = ["Brush Name", "Brush Stroke"] + .into_iter() + .map(|label| { + let (target_node, target_tree) = h.get_by_label(label).accesskit_node().locate(); + egui::Event::AccessKitActionRequest(egui::accesskit::ActionRequest { target_node, target_tree, action: egui::accesskit::Action::Click, data: None }) + }) + .collect(); + h.input_mut().events.extend(clicks); + h.run_steps(3); + let st = &h.state().ui.brush_picker_list; + assert_eq!((st.show_name, st.show_stroke, st.show_tip), (false, true, false), "the last part on stays on"); +} diff --git a/crates/ui-egui/src/brush_refusal_alert_tests.rs b/crates/ui-egui/src/brush_refusal_alert_tests.rs new file mode 100644 index 0000000000..7aa6bee9fa --- /dev/null +++ b/crates/ui-egui/src/brush_refusal_alert_tests.rs @@ -0,0 +1,106 @@ +//! #11898: when the Brush can't paint (hidden target layer, Lock All, a group's pixels), a press +//! opens the reference application's alert with OK and paints nothing; other tools keep today's +//! status-bar message, a group's targeted mask paints and Lock transparent pixels paints. + +use egui::Modifiers; +use serde_json::{Value, json}; + +use super::*; +use crate::canvas::{ToolEvent, tool_event}; + +/// A 64 × 64 document with a painted layer active, black foreground, `tool`. +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#000000"})).unwrap(); + app.ui.tool = tool; + app.sync_views(); + app +} + +fn active(app: &PhotocraftApp) -> u64 { + app.session.active().unwrap().active_layer.unwrap().0 +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +/// A press, a short drag and the release with the active tool. +fn stroke(app: &mut PhotocraftApp) { + tool_event(app, ToolEvent::Down { x: 20.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 44.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 44.0, y: 32.0 }, Modifiers::NONE); +} + +fn alerts(app: &PhotocraftApp) -> Vec { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(Value::as_str).map(str::to_string)).collect() +} + +fn refused(app: &mut PhotocraftApp, want: &str) { + let before = steps(app); + stroke(app); + assert_eq!(alerts(app), [want], "the alert, once"); + assert_eq!(steps(app), before, "nothing painted, no History step"); + // Over the control channel it is an ordinary dialog: `ui.dialog.confirm` closes it. + let id = app.ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).unwrap(); + crate::dialogs::confirm(app, id).unwrap(); + assert!(alerts(app).is_empty()); +} + +#[test] +fn a_hidden_target_layer() { + let mut app = app(Tool::Brush); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + refused(&mut app, "Could not use the brush tool because the target layer is hidden."); + assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); +} + +#[test] +fn lock_all() { + let mut app = app(Tool::Brush); + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + refused(&mut app, "Could not use the brush tool because the layer is locked."); +} + +#[test] +fn a_group_is_active() { + let mut app = app(Tool::Brush); + app.run("layer.new.group", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(active(&app))).unwrap().is_group()); + refused(&mut app, "Could not use the brush tool because the pixels in a group cannot be edited without merging the group."); +} + +#[test] +fn a_groups_targeted_mask_and_lock_transparency_still_paint() { + let mut app = app(Tool::Brush); + app.run("layer.new.group", json!({})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + assert_eq!(crate::canvas::paint_target(&app), json!("mask"), "the new mask is the target"); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "no alert on the mask"); + assert_eq!(steps(&app), before + 1, "the mask was painted"); + let mut app = self::app(Tool::Brush); + app.run("layer.lockLayers", json!({"transparency": true})).unwrap(); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + assert_eq!(steps(&app), before + 1, "paints on the existing pixels"); +} + +#[test] +fn other_tools_keep_the_status_bar() { + // Wording not measured for them: today's message, no dialog. + let mut app = app(Tool::Pencil); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + assert_eq!(app.ui.status, photocraft_engine::hidden_target::HIDDEN); + assert_eq!(tool_name(Tool::Pencil), None); + assert_eq!(tool_name(Tool::Brush), Some("brush tool"), "the one place that names the tool"); +} diff --git a/crates/ui-egui/src/cam_no_pixels_alert_tests.rs b/crates/ui-egui/src/cam_no_pixels_alert_tests.rs new file mode 100644 index 0000000000..66bba5a463 --- /dev/null +++ b/crates/ui-egui/src/cam_no_pixels_alert_tests.rs @@ -0,0 +1,203 @@ +//! #12192: with no selection, a Content-Aware Move drag that encloses no area (a straight line or a +//! click) warns "No pixels are selected." with "Don't show again", adds no History state and +//! selects nothing. A drag that encloses an area still makes the selection; the Lasso tool and a +//! drag with a selection keep their behaviour. + +use std::cell::RefCell; +use std::rc::Rc; + +use egui::Modifiers; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::{DialogKind, Tool}; + +/// A 200 x 100 white document with nothing selected and the Content-Aware Move tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap(); + app.ui.tool = Tool::ContentAwareMove; + app +} + +/// A drag through `points` (the first is the press), released at the last. +fn drag(app: &mut PhotocraftApp, points: &[[f64; 2]]) { + let m = Modifiers::NONE; + let [x, y] = points[0]; + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, m); + for &[x, y] in &points[1..] { + tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, m); + } + let [x, y] = points[points.len() - 1]; + tool_event(app, ToolEvent::Up { x, y }, m); +} + +const LINE: &[[f64; 2]] = &[[20.0, 50.0], [60.0, 50.0], [100.0, 50.0], [140.0, 50.0]]; +const DIAGONAL: &[[f64; 2]] = &[[20.0, 20.0], [50.0, 35.0], [80.0, 50.0], [110.0, 65.0]]; +const AREA: &[[f64; 2]] = &[[20.0, 20.0], [80.0, 20.0], [80.0, 80.0], [20.0, 80.0]]; + +/// The open "No pixels are selected." alerts. +fn alerts(app: &PhotocraftApp) -> Vec { + app.ui + .dialogs + .iter() + .filter(|d| d.kind == DialogKind::Error && d.fields.get("message").and_then(Value::as_str) == Some("No pixels are selected.")) + .map(|d| d.id) + .collect() +} + +/// Whether the document has a selection. +fn selected(app: &PhotocraftApp) -> bool { + app.session.active().unwrap().doc.selection.is_some() +} + +/// The number of History states. +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +#[test] +fn a_straight_line_or_a_click_warns_and_changes_nothing() { + for (name, points) in [("line", LINE), ("diagonal", DIAGONAL), ("click", &[[40.0, 40.0]][..]), ("two points", &[[40.0, 40.0], [90.0, 40.0]][..])] { + let mut app = app(); + let before = steps(&app); + drag(&mut app, points); + assert_eq!(alerts(&app).len(), 1, "{name}: the alert"); + assert!(!selected(&app), "{name}: nothing selected"); + assert_eq!(steps(&app), before, "{name}: no History state"); + } +} + +#[test] +fn a_second_drag_while_the_alert_is_open_adds_no_second_one() { + let mut app = app(); + drag(&mut app, LINE); + drag(&mut app, LINE); + assert_eq!(alerts(&app).len(), 1); +} + +#[test] +fn ok_closes_it_and_the_next_drag_warns_again() { + let mut app = app(); + drag(&mut app, LINE); + let id = alerts(&app)[0]; + // The alert's OK button answers as Cancel does (its only button); a script may confirm it. + crate::dialogs::cancel(&mut app, id).unwrap(); + assert!(alerts(&app).is_empty()); + drag(&mut app, LINE); + assert_eq!(alerts(&app).len(), 1, "the box was not ticked, so it warns again"); + let id = alerts(&app)[0]; + crate::dialogs::confirm(&mut app, id).unwrap(); + drag(&mut app, LINE); + assert_eq!(alerts(&app).len(), 1); +} + +#[test] +fn dont_show_again_stops_the_warning_and_is_kept_with_the_preferences() { + for confirm in [false, true] { + let mut app = app(); + let saved = Rc::new(RefCell::new(String::new())); + let store = saved.clone(); + app.services.save_prefs = Some(Box::new(move |text| { + *store.borrow_mut() = text.to_string(); + Ok(()) + })); + drag(&mut app, LINE); + let id = alerts(&app)[0]; + app.ui.dialog_mut(id).unwrap().fields.insert("skip".into(), json!(true)); + if confirm { + crate::dialogs::confirm(&mut app, id).unwrap(); + } else { + crate::dialogs::cancel(&mut app, id).unwrap(); + } + let text = saved.borrow().clone(); + let stored: Value = serde_json::from_str(&text).unwrap_or_else(|e| panic!("confirm {confirm}: the preferences were saved ({e})")); + assert_eq!(stored["dialogs"]["contentAwareMove.noPixelsSelected"], json!({"skip": true}), "confirm {confirm}: written to the store"); + let before = steps(&app); + drag(&mut app, LINE); + assert!(alerts(&app).is_empty(), "confirm {confirm}: no alert any more"); + assert!(!selected(&app) && steps(&app) == before, "confirm {confirm}: still nothing selected and no History state"); + // A restart reads it back from the store. + let services = crate::Services { load_prefs: Some(Box::new(move || Some(text.clone()))), ..Default::default() }; + let mut fresh = PhotocraftApp::new(photocraft_engine::Session::new(), services); + fresh.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap(); + fresh.ui.tool = Tool::ContentAwareMove; + drag(&mut fresh, LINE); + assert!(alerts(&fresh).is_empty(), "confirm {confirm}: no alert after a restart"); + } +} + +#[test] +fn a_tiny_lasso_that_covers_part_of_a_pixel_still_selects() { + // Under half a pixel of area, but anti-aliased it covers part of pixel 10,10. + let mut app = app(); + app.ui.tool_options.anti_alias = true; + let before = steps(&app); + drag(&mut app, &[[10.0, 10.0], [11.0, 10.0], [10.0, 10.75]]); + assert!(alerts(&app).is_empty()); + assert!(selected(&app)); + assert_eq!(steps(&app), before + 1); +} + +#[test] +fn without_anti_alias_a_lasso_over_pixel_centres_selects() { + let mut app = app(); + app.ui.tool_options.anti_alias = false; + let before = steps(&app); + drag(&mut app, &[[10.0, 20.0], [13.0, 20.0], [13.0, 23.0], [10.0, 23.0]]); + assert!(alerts(&app).is_empty()); + assert!(selected(&app)); + assert_eq!(steps(&app), before + 1); +} + +#[test] +fn a_thin_lasso_between_pixel_centres_warns_without_anti_alias() { + // 21 px² of area, but between the centres of row 20 (20.5) and the row above: no pixel. + let mut app = app(); + app.ui.tool_options.anti_alias = false; + let before = steps(&app); + drag(&mut app, &[[10.0, 20.1], [150.0, 20.1], [150.0, 20.4]]); + assert_eq!(alerts(&app).len(), 1); + assert!(!selected(&app)); + assert_eq!(steps(&app), before); +} + +#[test] +fn a_drag_that_encloses_an_area_still_selects_it() { + let mut app = app(); + let before = steps(&app); + drag(&mut app, AREA); + assert!(alerts(&app).is_empty()); + assert!(selected(&app)); + assert_eq!(steps(&app), before + 1); +} + +#[test] +fn the_lasso_tool_does_not_warn() { + let mut app = app(); + app.ui.tool = Tool::Lasso; + drag(&mut app, LINE); + drag(&mut app, &[[40.0, 40.0]]); + assert!(alerts(&app).is_empty()); +} + +#[test] +fn with_a_selection_a_line_outside_it_keeps_todays_behaviour() { + let mut app = app(); + app.run("select.rect", json!({"x": 150, "y": 10, "width": 30, "height": 30})).unwrap(); + drag(&mut app, LINE); + assert!(alerts(&app).is_empty(), "not measured with a selection: no alert"); +} + +#[test] +fn other_alerts_have_no_dont_show_again() { + let mut app = app(); + let mut fields = serde_json::Map::new(); + fields.insert("message".into(), json!("Something else.")); + let id = app.ui.open_dialog(DialogKind::Error, fields); + app.ui.dialog_mut(id).unwrap().fields.insert("skip".into(), json!(true)); + let before = app.session.prefs().dialogs.clone(); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(app.session.prefs().dialogs, before, "an alert without the box keeps no preference"); +} diff --git a/crates/ui-egui/src/cam_options_bar_tests.rs b/crates/ui-egui/src/cam_options_bar_tests.rs new file mode 100644 index 0000000000..e4080c1938 --- /dev/null +++ b/crates/ui-egui/src/cam_options_bar_tests.rs @@ -0,0 +1,187 @@ +//! #12193: Content-Aware Move's Structure and Color open a whole-number slider popup, the bar's +//! controls carry the reference tooltips, a typed value outside the range alerts and keeps the +//! closest value, and a live Transform On Drop box greys the bar with Cancel then Commit at the +//! right end. Changing these controls is not a history state. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +use super::{COLOR_RANGE_ALERT, STRUCTURE_RANGE_ALERT}; + +fn app_harness(live_box: bool) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap(); + app.ui.tool = Tool::ContentAwareMove; + if live_box { + app.ui.tool_options.cam_transform_on_drop = true; + assert!(crate::cam_transform::begin(&mut app, [20, 8]), "the dropped patch gets a box"); + } + app + }); + h.run_steps(5); + h +} + +fn spin<'a>(h: &'a Harness<'static, PhotocraftApp>, label: &str) -> egui_kittest::Node<'a> { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("the {label} field")) +} + +/// Types `text` into the named field, then leaves it with Tab or Enter. +fn type_field(h: &mut Harness<'static, PhotocraftApp>, label: &str, text: &str, key: egui::Key) { + spin(h, label).click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(key); + h.run_steps(3); +} + +fn alert(h: &Harness<'static, PhotocraftApp>) -> Option { + h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).and_then(|d| d.fields.get("message")).and_then(|m| m.as_str()).map(str::to_owned) +} + +fn steps(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +fn click_at(h: &mut Harness<'static, PhotocraftApp>, p: egui::Pos2) { + h.hover_at(p); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); +} + +#[test] +fn structure_and_color_default_to_whole_numbers_and_open_a_slider() { + let mut h = app_harness(false); + assert_eq!(h.state().ui.tool_options.cam_structure, 4.0); + assert_eq!(h.state().ui.tool_options.cam_color, 0.0); + assert_eq!(spin(&h, "Structure:").accesskit_node().numeric_value(), Some(4.0)); + assert_eq!(spin(&h, "Color:").accesskit_node().numeric_value(), Some(0.0)); + assert!(h.query_all_by_role(Role::Slider).next().is_none(), "the slider stays closed"); + let before = steps(&h); + h.get_by_role_and_label(Role::Button, "Structure").click(); + h.run_steps(4); + let slider = h.get_by_role_and_label(Role::Slider, "Structure").rect(); + click_at(&mut h, egui::pos2(slider.right() - 3.0, slider.center().y)); + assert_eq!(h.state().ui.tool_options.cam_structure, 7.0, "the slider's far end is 7"); + assert_eq!(h.state().ui.tool_options.cam_structure.fract(), 0.0); + assert_eq!(alert(&h), None, "the slider does not alert"); + assert_eq!(steps(&h), before, "the slider is not a history state"); + h.get_by_role_and_label(Role::Button, "Color").click(); + h.run_steps(4); + let color = h.get_by_role_and_label(Role::Slider, "Color").rect(); + click_at(&mut h, egui::pos2(color.right() - 3.0, color.center().y)); + assert_eq!(h.state().ui.tool_options.cam_color, 10.0); + assert_eq!(h.state().ui.tool_options.cam_color.fract(), 0.0); + assert_eq!(steps(&h), before); +} + +#[test] +fn a_typed_value_outside_the_range_alerts_and_keeps_the_closest() { + for (label, typed, key, want, message) in [ + ("Structure:", "99", egui::Key::Enter, 7.0, STRUCTURE_RANGE_ALERT), + ("Structure:", "0", egui::Key::Tab, 1.0, STRUCTURE_RANGE_ALERT), + ("Color:", "99", egui::Key::Enter, 10.0, COLOR_RANGE_ALERT), + ("Color:", "-5", egui::Key::Tab, 0.0, COLOR_RANGE_ALERT), + ] { + let mut h = app_harness(false); + let before = steps(&h); + type_field(&mut h, label, typed, key); + let got = if label.starts_with("Structure") { h.state().ui.tool_options.cam_structure } else { h.state().ui.tool_options.cam_color }; + assert_eq!(got, want, "{label} {typed}"); + assert_eq!(alert(&h).as_deref(), Some(message), "{label} {typed}"); + assert_eq!(steps(&h), before, "{label} {typed}: not a history state"); + h.get_by_label("OK").click(); + h.run_steps(4); + assert_eq!(alert(&h), None, "{label} {typed}: OK closes the alert"); + let got = if label.starts_with("Structure") { h.state().ui.tool_options.cam_structure } else { h.state().ui.tool_options.cam_color }; + assert_eq!(got, want, "{label} {typed}: the closest value stays"); + } +} + +#[test] +fn a_typed_value_inside_the_range_is_a_whole_number_without_an_alert() { + let mut h = app_harness(false); + let before = steps(&h); + type_field(&mut h, "Structure:", "4.2", egui::Key::Tab); + assert_eq!(h.state().ui.tool_options.cam_structure, 4.0); + type_field(&mut h, "Structure:", "6", egui::Key::Enter); + assert_eq!(h.state().ui.tool_options.cam_structure, 6.0); + type_field(&mut h, "Color:", "3.6", egui::Key::Tab); + assert_eq!(h.state().ui.tool_options.cam_color, 4.0); + type_field(&mut h, "Color:", "10", egui::Key::Enter); + assert_eq!(h.state().ui.tool_options.cam_color, 10.0); + type_field(&mut h, "Color:", "0", egui::Key::Tab); + assert_eq!(h.state().ui.tool_options.cam_color, 0.0); + assert_eq!(alert(&h), None); + assert_eq!(steps(&h), before); +} + +#[test] +fn the_bar_has_the_reference_tooltips() { + for (role, label, tip) in [ + (Role::ComboBox, "Mode:", "Choose a remix mode"), + (Role::SpinButton, "Structure:", "Adjust how strictly the source structure is preserved"), + (Role::SpinButton, "Color:", "Adjust how much the source color can be modified"), + (Role::CheckBox, "Sample All Layers", "Enable to remix all layers"), + (Role::CheckBox, "Transform On Drop", "Allows rotation and scaling of selection"), + ] { + let mut h = app_harness(false); + assert!(h.query_by_label(tip).is_none(), "{label}: no tooltip before the hover"); + let at = h.query_all_by_role(role).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("{label}")).rect().center(); + h.hover_at(at); + // The tooltip waits out its delay; the harness steps at 1/60 s. + h.run_steps(60); + assert!(h.query_by_label(tip).is_some(), "{label}: resting on it shows {tip:?}"); + } +} + +#[test] +fn a_live_transform_box_greys_the_bar_and_puts_cancel_then_commit_at_the_right() { + let h = app_harness(false); + assert!(h.query_by_label("Commit transform").is_none()); + assert!(h.query_by_label("Cancel transform").is_none()); + assert!(h.query_by_label("Lasso around an area, then drag the selection").is_some()); + + let mut h = app_harness(true); + for (role, label) in [ + (Role::Button, "New selection"), + (Role::ComboBox, "Mode:"), + (Role::SpinButton, "Structure:"), + (Role::SpinButton, "Color:"), + (Role::CheckBox, "Sample All Layers"), + (Role::CheckBox, "Transform On Drop"), + ] { + let node = h.query_all_by_role(role).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("{label}")); + assert!(node.accesskit_node().is_disabled(), "{label} is greyed while the box is up"); + } + assert!(h.query_by_label("Lasso around an area, then drag the selection").is_none()); + let cancel = h.get_by_label("Cancel transform"); + let commit = h.get_by_label("Commit transform"); + assert!(!cancel.accesskit_node().is_disabled() && !commit.accesskit_node().is_disabled()); + let (cancel, commit) = (cancel.rect(), commit.rect()); + assert!(cancel.right() <= commit.left() + 1.0, "Cancel then Commit: {cancel:?} {commit:?}"); + let sample = h.get_by_role_and_label(Role::CheckBox, "Transform On Drop").rect(); + assert!(cancel.left() > sample.right(), "the pair sits to the right of the controls"); + assert!(commit.right() > 1200.0, "Commit is at the right end of the bar: {commit:?}"); + + let before = steps(&h); + h.get_by_label("Cancel transform").click(); + h.run_steps(4); + assert!(!crate::cam_transform::active(h.state())); + assert_eq!(steps(&h), before, "Cancel drops the box without a history state"); + assert!(!spin(&h, "Structure:").accesskit_node().is_disabled(), "the bar is usable again"); +} diff --git a/crates/ui-egui/src/cam_transform_on_drop_default_tests.rs b/crates/ui-egui/src/cam_transform_on_drop_default_tests.rs new file mode 100644 index 0000000000..dc9ff9c840 --- /dev/null +++ b/crates/ui-egui/src/cam_transform_on_drop_default_tests.rs @@ -0,0 +1,86 @@ +//! Content-Aware Move › Transform On Drop starts on (#12185): a fresh start and Reset Tool give +//! the checkbox on, a drop shows the scale and rotate box, Enter commits a plain move and Escape +//! cancels it. A saved `false` stays off; a missing key takes the new default. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::{Tool, ToolOptions}; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 60})).unwrap(); + app.run("paint.pencil", json!({"points": [[16, 30], [28, 30]], "size": 4, "color": "#0000ff"})).unwrap(); + app.run("select.rect", json!({"x": 6, "y": 14, "width": 32, "height": 32})).unwrap(); + app.ui.tool = Tool::ContentAwareMove; + app +} + +fn blue(app: &PhotocraftApp, x: i32, y: i32) -> bool { + let st = app.session.active().unwrap(); + let layer = st.active_layer.and_then(|id| st.doc.layer(id)).unwrap(); + layer.surface().unwrap().rgba(x, y)[0] < 0.5 +} + +fn drop_patch(app: &mut PhotocraftApp) { + let m = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: 22.0, y: 30.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Move { x: 72.0, y: 30.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: 72.0, y: 30.0 }, m); +} + +#[test] +fn fresh_start_and_reset_tool_leave_transform_on_drop_on() { + assert!(ToolOptions::default().cam_transform_on_drop); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert!(app.ui.tool_options.cam_transform_on_drop, "a fresh start leaves Transform On Drop on"); + app.ui.tool = Tool::ContentAwareMove; + app.ui.tool_options.cam_transform_on_drop = false; + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tools::tool_reset::RESET, json!({})).unwrap(); + assert!(app.ui.tool_options.cam_transform_on_drop, "Reset Tool turns Transform On Drop back on"); +} + +#[test] +fn a_stored_false_stays_off_and_a_missing_key_is_on() { + let mut v = serde_json::to_value(ToolOptions::default()).unwrap(); + v["cam_transform_on_drop"] = json!(false); + let stored: ToolOptions = serde_json::from_value(v.clone()).unwrap(); + assert!(!stored.cam_transform_on_drop, "a saved false stays off"); + v.as_object_mut().unwrap().remove("cam_transform_on_drop"); + let missing: ToolOptions = serde_json::from_value(v).unwrap(); + assert!(missing.cam_transform_on_drop, "a missing key takes the new default"); +} + +#[test] +fn a_drop_shows_the_box_enter_commits_a_plain_move_and_escape_cancels() { + let mut app = app(); + assert!(app.ui.tool_options.cam_transform_on_drop); + let steps = app.session.active().unwrap().history.past_len(); + drop_patch(&mut app); + assert!(crate::cam_transform::active(&app), "the drop shows the box"); + assert!(blue(&app, 22, 30) && !blue(&app, 72, 30), "the document waits"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + let place = crate::cam_transform::placement(app.ui.cam_transform.as_ref().unwrap()).unwrap(); + assert!(place.is_plain_move()); + let p = crate::cam_transform::params(&app, &place); + assert!(p.get("scaleX").is_none() && p.get("scaleY").is_none() && p.get("rotate").is_none(), "a plain move sends no scale or rotate: {p}"); + assert_eq!(p["offset"], json!([50, 0])); + + crate::cam_transform::cancel(&mut app); + assert!(!crate::cam_transform::active(&app)); + assert!(blue(&app, 22, 30) && !blue(&app, 72, 30), "Escape cancels the move"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps); + assert_ne!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.contentAwareMove")); + + drop_patch(&mut app); + assert!(crate::cam_transform::active(&app)); + crate::cam_transform::commit(&mut app); + assert!(!crate::cam_transform::active(&app) && !app.ui.status_error, "{}", app.ui.status); + let (id, sent) = app.session.journal.last().cloned().unwrap(); + assert_eq!(id, "paint.contentAwareMove"); + assert_eq!(sent["offset"], json!([50, 0])); + assert!(sent.get("scaleX").is_none() && sent.get("scaleY").is_none() && sent.get("rotate").is_none(), "{sent}"); + assert!(blue(&app, 72, 30) && !blue(&app, 22, 30), "Enter commits the plain move"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 88e69f1e4c..3c96a48ed8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -39,6 +39,7 @@ pub mod pixel_grid; pub mod quick_pick; pub mod rotate_view; pub mod rulers; +pub mod scroll_all_windows; pub mod scrollbars; pub mod select_mask_view; mod selection; @@ -62,8 +63,10 @@ pub mod zoom_window_fit; #[cfg(test)] pub(crate) use cursors::eyedropper_ring_colors; -pub(crate) use cursors::{alt_picks, alt_samples, composite_color, paint_bucket_cursor, pen_cursor, pencil_cursor_rect, pencil_tip_is_round, pipette_cursor}; -use cursors::{brush_tip_centre, eyedropper_ring, precise_other_cursor, visible_crosshair}; +pub(crate) use cursors::{ + alt_picks, alt_samples, composite_color, paint_bucket_cursor, pen_cursor, pencil_cursor_rect, pencil_tip_is_round, pipette_cursor, precise_other_cursor, +}; +use cursors::{brush_tip_centre, eyedropper_ring, preview_locator_cursor, visible_crosshair}; pub(crate) use display::GPU_OUTPUT; use display::texture_key; pub(crate) use display::{cache_key, canvas_display, display_doc, display_image}; @@ -694,6 +697,8 @@ struct DialogCanvasInput<'a> { temporary: Option, free_hover: bool, img_rect: Rect, + idx: usize, + aspect: f32, } fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput<'_>) { @@ -717,6 +722,10 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< input.primary && app.ui.dialogs.last().is_some_and(|d| crate::select_mask_view::owns(&d.fields) && crate::select_mask_view::brush_on(&d.fields)); // Field Blur's pins are placed and dragged on the image (`blur_pins`). let pinning = input.primary && app.ui.dialogs.last().is_some_and(|d| crate::blur_pins::owns(&d.fields)); + // A filter dialog with a preview window (Smart Sharpen, Unsharp Mask, Reduce Noise…): the image + // is its locator, and a click centres the window there (#9648), whatever the tool. Only the + // press counts: as in the reference application, dragging on afterwards leaves the window be. + let locating = input.primary && crate::filter_preview_ui::locator(app).is_some(); // Layer Style on a Drop or Inner Shadow page: a drag on the image moves the shadow (#5701). let shadow_drag = !picking && app.ui.dialogs.last().is_some_and(|d| d.kind == crate::state::DialogKind::LayerStyle && crate::layer_style::drags_shadow(&d.fields)); @@ -752,6 +761,7 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< && !range_picking && !refine_brushing && !pinning + && !locating && !shadow_drag && !gradient_drag && curve_point_press.is_none(); @@ -777,8 +787,14 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< } } else if let Some(d) = crate::dialogs::pan_delta(input.ctx, input.rect, dialog_hand) { let d = input.xf.unmap_vec(d) / (input.view.zoom / input.ppp); + let before = input.view.center; input.view.center[0] -= d.x; input.view.center[1] -= d.y; + // Hand › Scroll All Windows, or Shift held: the other shown views follow, as on the free canvas. + let scroll_all = crate::scroll_all_windows::active(app, crate::workspace_ui::sticky_mods(app, input.ctx.input(|i| i.modifiers)).shift); + let source = crate::scroll_all_windows::source(app, input.idx); + let geometry = crate::scroll_all_windows::ClampGeometry { size: input.rect.size(), ppp: input.ppp, aspect: input.aspect }; + crate::scroll_all_windows::follow_step(app, scroll_all, source, before, input.view, geometry); input.ctx.set_cursor_icon(crate::tool_cursor::hand(input.ctx, true)); } else if input.free_hover && (input.space_pan || dialog_hand) { input.ctx.set_cursor_icon(crate::tool_cursor::hand(input.ctx, false)); @@ -824,6 +840,15 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< { let press = crate::dialogs::free_press(input.ctx, input.rect); crate::blur_pins::canvas(app, input.ctx, input.xf, p, press); + } else if locating + && !input.middle + && let Some(p) = crate::dialogs::free_pointer_over(input.ctx, input.rect) + { + input.ctx.set_cursor_icon(preview_locator_cursor(input.ctx, p)); + if let Some(q) = crate::dialogs::free_press(input.ctx, input.rect).filter(|_| input.ctx.input(|i| i.pointer.primary_pressed())) { + let d = input.xf.to_doc(q); + crate::filter_preview_ui::center_at(app, d[0], d[1]); + } } else if refine_brushing && !input.middle && let Some(p) = crate::dialogs::free_pointer_over(input.ctx, input.rect) @@ -862,6 +887,7 @@ struct CanvasToolInput<'a> { space_hand: bool, ppp: f32, under_dialog: bool, + menu_dismiss_press: bool, zoom_out: &'a dyn Fn(bool) -> bool, display_zoom: f32, } @@ -881,9 +907,22 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: // (Preferences › Tools, `paint_mouse`). crate::paint_mouse::sync_tool_brush(app); let mut buttons = crate::paint_mouse::canvas_buttons(app, response, tool); + if input.menu_dismiss_press { + // Navigation and drags read `buttons` directly (zoom holds and drags, Rotate View): + // starve them. The release click stays armed, so the click handling below consumes + // it through the flag. + buttons.started = false; + buttons.dragged = false; + buttons.stopped = false; + } // The Crop tool's frame is edited from the press (before egui's drag threshold), so the // pixels past the canvas show at once, as in Photoshop. - if tool == Tool::Crop && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_down()) && crate::crop_ui::press(app) { + if tool == Tool::Crop + && !input.menu_dismiss_press + && response.is_pointer_button_down_on() + && ui.input(|i| i.pointer.primary_down()) + && crate::crop_ui::press(app) + { ctx.request_repaint(); } // Capture intent at the press, before egui's drag threshold or click replay on release: @@ -892,6 +931,7 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: tool.is_type() || matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee | Tool::ObjectSelection); let tool_press = egui::Id::unique(("tool-pointer-press-modifiers", idx)); if capture_press + && !input.menu_dismiss_press && let Some((p, press_mods)) = ui.input(|i| { i.events.iter().find_map(|e| match e { egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers } if rect.contains(*pos) => Some((*pos, *modifiers)), @@ -911,6 +951,17 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: handle_canvas_tool_navigation(app, ui, view, input, &mut buttons); handle_canvas_tool_stroke(app, ui, input, mods, capture_press, tool_press, &mut buttons); handle_canvas_tool_clicks(app, ui, view, input, mods, tool_press, &buttons); + // Clear the menu-dismissal flag on the gesture's pointer release, even when the release + // occurs outside the canvas and produces no `buttons.clicked` event. It sits below (not + // above) the click handling, so a release over the canvas in a later frame is first + // consumed by the flag check there: clearing before it would let that release zoom + // (CodeRabbit, #9841). The all-buttons-up check also covers a release that landed in a + // frame this canvas didn't render. + if app.ui.canvas_tool_menu_dismissed + && (ui.input(|i| i.pointer.primary_released()) || ui.input(|i| i.pointer.secondary_released()) || !ui.input(|i| i.pointer.any_down())) + { + app.ui.canvas_tool_menu_dismissed = false; + } } fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_>, mods: egui::Modifiers, buttons: &mut crate::paint_mouse::Buttons) { @@ -937,8 +988,11 @@ fn handle_canvas_tool_menus(app: &mut PhotocraftApp, input: &CanvasToolInput<'_> }; // The Lasso (and the Freeform Pen, which draws the same way) reads its own presses and // drops the moves of a drag it didn't start, so an open Free Transform box takes the - // usual drag path instead (#2153). - if crate::lasso_ui::owns(tool) && !transform_owns_pointer { + // usual drag path instead (#2153). It reads the raw pointer events straight from the + // context, so the `buttons` starvation above never reaches it: a press that dismisses the + // canvas tool menu would draw a selection. Gate the dispatcher itself, as the Crop press + // above is gated (#9841). + if crate::lasso_ui::owns(tool) && !transform_owns_pointer && !input.menu_dismiss_press { crate::lasso_ui::canvas_input(app, ctx, xf, response); (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); } @@ -1027,10 +1081,11 @@ fn handle_canvas_tool_navigation( (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); } // Animated Zoom: a Zoom press held still zooms continuously (zoom_hold.rs); while it does, - // it owns the press: no scrub, and its release is no click step. + // it owns the press: no scrub, and its release is no click step. A menu-dismissal press + // must not arm it: holding the dismissal click would zoom (CodeRabbit, #9841). if tool == Tool::Zoom && !transform_owns_pointer { let out = zoom_out(ui.input(|i| i.modifiers.alt)); - let on_canvas = !input.under_dialog && !over_compass && response.is_pointer_button_down_on(); + let on_canvas = !input.menu_dismiss_press && !input.under_dialog && !over_compass && response.is_pointer_button_down_on(); let hold = crate::zoom_hold::hold_id(idx, primary, ctx.viewport_id()); if crate::zoom_hold::update(ctx, view, xf, app.session.prefs().general.animated_zoom, out, ppp, on_canvas, hold) { (buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false); @@ -1072,6 +1127,7 @@ fn handle_canvas_tool_stroke( let right_down = ui.input(|i| i.pointer.secondary_down()) || physical_right; if strokes_live(tool) && !right_down + && !input.menu_dismiss_press && app.drag.is_none() && response.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_pressed()) @@ -1091,6 +1147,7 @@ fn handle_canvas_tool_stroke( buttons.started = false; } if buttons.started + && !input.menu_dismiss_press && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)).or(response.interact_pointer_pos()) { // A press the controls refused (the Background among the layers) goes nowhere else (#11101). @@ -1105,7 +1162,7 @@ fn handle_canvas_tool_stroke( // recognises a drag (past its click distance): otherwise the first few points are lost // and the stroke starts with a straight segment and no pressure ramp. let press_stroke_moving = press_stroke && app.drag.is_some(); - if buttons.dragged || buttons.stopped || press_stroke_moving { + if !input.menu_dismiss_press && (buttons.dragged || buttons.stopped || press_stroke_moving) { // Feed every pointer move the OS delivered this frame, not just the latest position, so // a fast stroke is sampled densely and renders as a smooth curve instead of a coarse // polyline. egui-winit pushes one `PointerMoved` per `CursorMoved`, and they accumulate @@ -1163,7 +1220,7 @@ fn handle_canvas_tool_stroke( feed_live_stroke(app); crate::magnetic_lasso_ui::flush(app); } - if buttons.stopped { + if buttons.stopped && !input.menu_dismiss_press { // The live painting press already created the stroke and this release commits it. // egui may also report clicked on the same release; replaying that click paints a // second full-pressure dab over the real (possibly light-pressure) pen dab. @@ -1188,7 +1245,7 @@ fn handle_canvas_tool_stroke( } // A stroke started on the press ends with the release, whether egui saw a drag, a click, // or neither (a long press that never moved). - if press_stroke && !buttons.stopped && ui.input(|i| i.pointer.primary_released()) { + if press_stroke && !buttons.stopped && !input.menu_dismiss_press && ui.input(|i| i.pointer.primary_released()) { buttons.clicked = false; let p = response.interact_pointer_pos().map(|p| xf.to_doc(p)).or_else(|| app.drag.as_ref().and_then(|d| d.points.last().map(|q| [q[0], q[1]]))); if let Some(d) = p @@ -1221,66 +1278,17 @@ fn handle_canvas_tool_clicks( let ppp = input.ppp; let zoom_out = input.zoom_out; let display_zoom = input.display_zoom; - if buttons.clicked - && let Some(p) = response.interact_pointer_pos() + // Magnetic Lasso: between clicks the border follows the pointer with the button up. This is a + // pointer-only gesture — `canvas_buttons` makes `clicked` false on frames without a button + // event — so it must stay outside the click-only branch below, or live edge tracking and + // automatic fastening freeze until the next click. A menu-dismissal gesture is inert, so the + // hover is suppressed with the same flag that starves the rest of the input pass (#9841). + if tool == Tool::MagneticLasso + && app.ui.magnetic.active() + && !input.menu_dismiss_press + && !(buttons.started || buttons.dragged || buttons.stopped) + && response.hovered() { - let click_button = if app.secondary_erase { PointerButton::Secondary } else { PointerButton::Primary }; - let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods); - let click_mods = if tool == Tool::ObjectSelection && click_button == PointerButton::Primary { - ctx.data(|d| d.get_temp(tool_press)).unwrap_or(click_mods) - } else { - click_mods - }; - let d = xf.to_doc(p); - match tool { - Tool::Zoom if !transform_owns_pointer => { - let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size); - let center = app.session.prefs().tools.zoom_clicked_point_to_center; - let doc_anchor = xf.to_doc(p); - let screen_anchor = p; - zoom_about(view, xf, p, nz, center, ppp); - view.request_zoom_animation(app.session.prefs().general.animated_zoom && nz != display_zoom); - view.zoom_anchor = (view.zoom_animating && !center).then_some((doc_anchor, [screen_anchor.x, screen_anchor.y])); - } - // A click with the (temporary) Hand does nothing, never the tool underneath. - Tool::Hand | Tool::RotateView => {} - // Double-clicking closes the polygonal lasso: the first click placed the last - // vertex (or already closed it), so the second never starts a new polygon. egui - // reports it as a triple click when a vertex went down shortly before. - Tool::PolygonLasso if response.double_clicked() || response.triple_clicked() => commit_polygon(app), - // The same for the Magnetic Lasso: along the edges, or straight with ⌥. - Tool::MagneticLasso if response.double_clicked() || response.triple_clicked() => crate::magnetic_lasso_ui::close(app, mods.alt), - // The first click placed (or grabbed) the point; the second toggles it. - Tool::CurvaturePen if response.double_clicked() => crate::vector_ui::curvature_toggle(app, d[0], d[1]), - // Double-clicking a guide opens Preferences › Guides, Grid & Slices, as in Photoshop. - Tool::Move if response.double_clicked() && crate::rulers::guide_at(app, d[0], d[1]).is_some() => { - if let Err(e) = crate::menus::invoke(app, ctx, "edit.preferences.guidesGridAndSlices", json!({})) { - app.ui.status = e; - } - } - // A click the transform controls refused (the Background among the layers) goes - // nowhere else (#11101). - _ if tool == Tool::Move && app.ui.transform.is_none() && begin_transform_controls_at(app, ctx, xf, p) == ControlsPress::Refused => {} - _ => { - // If this tool was not handled on pointer-down, fall back to a - // click-sized gesture while preserving pen pressure (mouse stays at 1). - tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, click_mods); - tap_at_peak_pressure(app); - tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, click_mods); - } - } - } - // A Frame drag uses a temporary Free Transform for its image/both target. That owns - // the release, so the generic tool-click gate can be false even for a double click. - if tool == Tool::Frame - && response.contains_pointer() - && ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)) - && let Some(p) = response.interact_pointer_pos().or_else(|| ctx.pointer_hover_pos()) - { - crate::frame_tool::double_click(app, xf.to_doc(p)); - } - // Magnetic Lasso: between clicks the border follows the pointer with the button up. - if tool == Tool::MagneticLasso && app.ui.magnetic.active() && !(buttons.started || buttons.dragged || buttons.stopped) && response.hovered() { let moves: Vec = ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect()); app.defer_live_stroke = true; for p in moves.into_iter().filter(|p| rect.contains(*p)) { @@ -1290,17 +1298,87 @@ fn handle_canvas_tool_clicks( app.defer_live_stroke = false; crate::magnetic_lasso_ui::flush(app); } - // Move tool: a double-click on type edits it, as in Photoshop (#1132). Only the selected - // Move tool, not ⌘ held over another tool; an open transform box keeps its double-click - // (commit, below). - if tool == Tool::Move - && app.ui.tool == Tool::Move - && app.ui.transform.is_none() - && response.double_clicked() + if buttons.clicked && let Some(p) = response.interact_pointer_pos() { - let d = xf.to_doc(p); - crate::type_tool::edit_at(app, d[0], d[1]); + // If an outside press dismissed the canvas tool menu, consume this release click + // so it doesn't also trigger a tool action (Photoshop behavior). A click outside a + // still-open menu dismisses it and is consumed the same way (CodeRabbit, #9841). + if app.ui.canvas_tool_menu_dismissed { + app.ui.canvas_tool_menu_dismissed = false; + } else if let Some(menu_rect) = crate::canvas_tool_menu::menu_rect_if_open(app, ctx) + && !menu_rect.contains(p) + { + // The click is outside the open menu: it dismisses the menu, no tool action. + } else { + let click_button = if app.secondary_erase { PointerButton::Secondary } else { PointerButton::Primary }; + let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods); + let click_mods = if tool == Tool::ObjectSelection && click_button == PointerButton::Primary { + ctx.data(|d| d.get_temp(tool_press)).unwrap_or(click_mods) + } else { + click_mods + }; + let d = xf.to_doc(p); + match tool { + Tool::Zoom if !transform_owns_pointer => { + let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size); + let center = app.session.prefs().tools.zoom_clicked_point_to_center; + let doc_anchor = xf.to_doc(p); + let screen_anchor = p; + zoom_about(view, xf, p, nz, center, ppp); + view.request_zoom_animation(app.session.prefs().general.animated_zoom && nz != display_zoom); + view.zoom_anchor = (view.zoom_animating && !center).then_some((doc_anchor, [screen_anchor.x, screen_anchor.y])); + } + // A click with the (temporary) Hand does nothing, never the tool underneath. + Tool::Hand | Tool::RotateView => {} + // Double-clicking closes the polygonal lasso: the first click placed the last + // vertex (or already closed it), so the second never starts a new polygon. egui + // reports it as a triple click when a vertex went down shortly before. + Tool::PolygonLasso if response.double_clicked() || response.triple_clicked() => commit_polygon(app), + // The same for the Magnetic Lasso: along the edges, or straight with ⌥. + Tool::MagneticLasso if response.double_clicked() || response.triple_clicked() => crate::magnetic_lasso_ui::close(app, mods.alt), + // The first click placed (or grabbed) the point; the second toggles it. + Tool::CurvaturePen if response.double_clicked() => crate::vector_ui::curvature_toggle(app, d[0], d[1]), + // Double-clicking a guide opens Preferences › Guides, Grid & Slices, as in Photoshop. + Tool::Move if response.double_clicked() && crate::rulers::guide_at(app, d[0], d[1]).is_some() => { + if let Err(e) = crate::menus::invoke(app, ctx, "edit.preferences.guidesGridAndSlices", json!({})) { + app.ui.status = e; + } + } + // A click the transform controls refused (the Background among the layers) goes + // nowhere else (#11101). + _ if tool == Tool::Move && app.ui.transform.is_none() && begin_transform_controls_at(app, ctx, xf, p) == ControlsPress::Refused => {} + _ => { + // If this tool was not handled on pointer-down, fall back to a + // click-sized gesture while preserving pen pressure (mouse stays at 1). + tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, click_mods); + tap_at_peak_pressure(app); + tool_event(app, ToolEvent::Up { x: d[0], y: d[1] }, click_mods); + } + } + } + // Move tool: a double-click on type edits it, as in Photoshop (#1132). Only the selected + // Move tool, not ⌘ held over another tool; an open transform box keeps its double-click + // (commit, below). + if tool == Tool::Move + && app.ui.tool == Tool::Move + && app.ui.transform.is_none() + && response.double_clicked() + && let Some(p) = response.interact_pointer_pos() + { + let d = xf.to_doc(p); + crate::type_tool::edit_at(app, d[0], d[1]); + } + } + + // A Frame drag uses a temporary Free Transform for its image/both target. That owns + // the release, so the generic tool-click gate can be false even for a double click. + if tool == Tool::Frame + && response.contains_pointer() + && ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)) + && let Some(p) = response.interact_pointer_pos().or_else(|| ctx.pointer_hover_pos()) + { + crate::frame_tool::double_click(app, xf.to_doc(p)); } // A double-click commits an open Free Transform only on the box (handles included); outside // it does nothing (#11100). @@ -1682,6 +1760,15 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & { crate::tool_cursor::close_path(painter, p) } + // Over an endpoint of an open path, the continue-path pointer (#9356). + Tool::Pen + if { + let [x, y] = xf.to_doc(p); + crate::vector_ui::continues_path_at(app, tool, x, y) + } => + { + crate::tool_cursor::continue_path(painter, p) + } // The pen tools: their own icon with its nib on the point, or the crosshair for // precise Other Cursors (#4639). Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => { @@ -2097,6 +2184,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: temporary, free_hover, img_rect, + idx, + aspect, }, ); } @@ -2107,6 +2196,15 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // box is only drawn and driven on the primary canvas. let transform_owns_pointer = primary && app.ui.transform.is_some() && temporary.is_none() && !middle; let hand_pan = tool == Tool::Hand && !transform_owns_pointer; + // A press outside an open canvas tool menu dismisses it (`canvas_tool_menu::show`, after this + // input pass) and the whole gesture is consumed until its release, as in Photoshop: no tool + // press, stroke, drag, pan or zoom step. The menu closes mid-frame (after this input pass), so + // the open-menu hit test covers the dismissal frame, and the flag persists the block for the + // frames after it, until the release clear below the click handling. It gates the Hand and + // flick pans below too: they read `response.dragged()` directly and never see `buttons` + // (CodeRabbit, #9841). + let menu_dismiss_press = app.ui.canvas_tool_menu_dismissed + || crate::canvas_tool_menu::menu_rect_if_open(app, &ctx).is_some_and(|r| ui.input(|i| i.pointer.press_origin()).is_some_and(|p| !r.contains(p))); // The Hand pans with a drag of any button, but the selected Hand's right button is its view // menu, as in Photoshop: a drag with that button alone is a right-click that moved, which // opens the menu instead, until it strays past a right-click's reach and pans after all @@ -2129,8 +2227,17 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: // Preferences › Tools › Enable Flick Panning: a Hand drag let go while moving glides on. let flick_id = egui::Id::unique(("pc-flick-pan", idx, primary, ctx.viewport_id())); let flick_on = app.session.prefs().tools.enable_flick_panning; - if let Some(d) = crate::flick_pan::frame(&ctx, flick_id, hand_drag && !stroke_dismissal, response.drag_delta(), flick_on) { + // Hand › Scroll All Windows, or Shift held (on the keyboard or in Window › Modifier Keys): the + // other shown views follow this one. + let scroll_all = hand_pan && crate::scroll_all_windows::active(app, crate::workspace_ui::sticky_mods(app, ctx.input(|i| i.modifiers)).shift); + let scroll_source = crate::scroll_all_windows::source(app, idx); + // A glide keeps the drag's choice after Space, Shift or the button is let go; a menu-dismissal + // press is no pan, so it neither arms the glide nor moves the other views. + let glide_scroll_all = + crate::scroll_all_windows::glide_choice(&ctx, flick_id.with("scroll-all"), hand_drag && !stroke_dismissal && !menu_dismiss_press, scroll_all); + if let Some(d) = crate::flick_pan::frame(&ctx, flick_id, hand_drag && !stroke_dismissal && !menu_dismiss_press, response.drag_delta(), flick_on) { let d = xf.unmap_vec(d) / (view.zoom / ppp); + let before = view.center; if d.is_finite() { view.zoom_animating = false; view.zoom_anchor = None; @@ -2141,13 +2248,18 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if !app.session.prefs().tools.overscroll && crate::scrollbars::clamp_view_with_aspect(&mut view, rect.size(), ppp, aspect) { ctx.data_mut(|m| m.get_temp_mut_or_default::(flick_id).stop()); } + let geometry = crate::scroll_all_windows::ClampGeometry { size: rect.size(), ppp, aspect }; + crate::scroll_all_windows::follow_step(app, glide_scroll_all, scroll_source, before, &view, geometry); } // A scroll or zoom while the right button is held moves the image under its press: no click. crate::paint_mouse::track_right_press_view(&response, &view, flip); - if hand_drag && !stroke_dismissal { + if hand_drag && !stroke_dismissal && !menu_dismiss_press { let d = xf.unmap_vec(response.drag_delta()) / (view.zoom / ppp); + let before = view.center; view.center[0] -= d.x; view.center[1] -= d.y; + let geometry = crate::scroll_all_windows::ClampGeometry { size: rect.size(), ppp, aspect }; + crate::scroll_all_windows::follow_step(app, scroll_all, scroll_source, before, &view, geometry); // The tool cursors below are skipped while panning: the fist is set here (#2196). ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, true)); } else if primary && !stroke_dismissal && temporary.is_none() && !middle && crate::layer_picker::armed(app).is_some() { @@ -2167,6 +2279,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: space_hand: space_pan, ppp, under_dialog, + menu_dismiss_press, zoom_out: &zoom_out, display_zoom: display_view.zoom, }; diff --git a/crates/ui-egui/src/canvas/cam_preview.rs b/crates/ui-egui/src/canvas/cam_preview.rs index 68cd29f02c..7fb5c790eb 100644 --- a/crates/ui-egui/src/canvas/cam_preview.rs +++ b/crates/ui-egui/src/canvas/cam_preview.rs @@ -236,6 +236,7 @@ mod tests { app.run("paint.pencil", json!({"points": [[16, 30], [28, 30]], "size": 4, "color": "#0000ff"})).unwrap(); app.run("select.lasso", json!({"points": [[6, 14], [38, 14], [38, 46], [6, 46]]})).unwrap(); app.ui.tool = Tool::ContentAwareMove; + app.ui.tool_options.cam_transform_on_drop = false; let m = egui::Modifiers::NONE; let steps = app.session.active().unwrap().history.past_len(); @@ -317,6 +318,7 @@ mod tests { app.run("paint.pencil", json!({"points": [[150, 160], [170, 160]], "size": 12, "color": "#0000ff"})).unwrap(); app.run("select.rect", json!({"x": 10, "y": 10, "width": 300, "height": 300})).unwrap(); app.ui.tool = Tool::ContentAwareMove; + app.ui.tool_options.cam_transform_on_drop = false; let m = egui::Modifiers::NONE; tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, m); tool_event(&mut app, ToolEvent::Move { x: 340.0, y: 100.0, pressure: 1.0 }, m); diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index d005d91c05..4222f4a3ea 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -55,6 +55,10 @@ pub struct CanvasToolMenu { /// becomes active, the index may name a different sampler, so the menu closes and Delete greys. #[serde(default)] pub sampler_at: Option<(usize, [f64; 2])>, + /// The Eyedropper's menu (#11747): the composite colour under the right-click, averaged with + /// the Sample Size, which its Copy Color rows put on the clipboard. `None` over transparency. + #[serde(default)] + pub color: Option<[f32; 3]>, } /// A misspelled word in the type layer being edited (`edit.checkSpelling`'s `list` entry). @@ -314,6 +318,7 @@ pub fn open_crop(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; crop: Some(users), sampler: None, sampler_at: None, + color: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -365,8 +370,8 @@ pub fn cycle_canvas_color(app: &mut PhotocraftApp, backward: bool) -> Result<(), app.run("prefs.set", json!({"values": {"interface.canvasColor": name}})).map(|_| ()) } -/// The Zoom and Hand tools' context menu: the fixed zooms of the View menu (plus the Hand tool's -/// Fill Screen), then the zoom steps last, in Photoshop's order (#6005). +/// The Zoom tool's context menu: the fixed zooms of the View menu (plus Fill Screen), then the +/// zoom steps last, in Photoshop's order (#6005). pub const VIEW_MENU: &[Row] = &[ Some(("Fit on Screen", "view.fitOnScreen")), Some(("Fill Screen", FILL_SCREEN)), @@ -378,6 +383,14 @@ pub const VIEW_MENU: &[Row] = &[ Some(("Zoom Out", "view.zoomOut")), ]; +/// The Hand tool's context menu: only the fixed zooms, as measured in the reference application (#12022). +pub const HAND_MENU: &[Row] = &[ + Some(("Fit on Screen", "view.fitOnScreen")), + Some(("100%", "view.actualPixels")), + Some(("200%", "view.twoHundredPercent")), + Some(("Print Size", "view.printSize")), +]; + /// The view menu's Fill Screen row. Photoshop has no View menu command for it, so the menu sets /// the view itself. pub const FILL_SCREEN: &str = "view.fillScreen"; @@ -394,8 +407,8 @@ pub const SELECTION_MENU: &[Row] = &[ Some(("Save Selection…", "select.saveSelection")), Some(("Make Work Path…", "select.toWorkPath")), None, - Some(("Layer via Copy", "layer.new.layerViaCopy")), - Some(("Layer via Cut", "layer.new.layerViaCut")), + Some(("Layer Via Copy", "layer.new.layerViaCopy")), + Some(("Layer Via Cut", "layer.new.layerViaCut")), Some(("New Layer…", "layer.new.layer")), None, Some(("Free Transform", "edit.freeTransform")), @@ -422,6 +435,43 @@ pub const NO_SELECTION_MENU: &[Row] = &[ Some(("Load Selection…", "select.loadSelection")), ]; +/// The Eyedropper's copy rows (#11747). +pub const EYEDROPPER_COPY_HTML: &str = "canvasMenu.eyedropper.copyHtml"; +pub const EYEDROPPER_COPY_HEX: &str = "canvasMenu.eyedropper.copyHex"; + +/// The Eyedropper's canvas menu, in the reference application's order (#11747): the Sample Sizes +/// (the current one checked), then the two Copy Color rows for the colour under the pointer. +pub const EYEDROPPER_MENU: &[Row] = &[ + Some(("Point Sample", "canvasMenu.eyedropper.size.1")), + Some(("3 by 3 Average", "canvasMenu.eyedropper.size.3")), + Some(("5 by 5 Average", "canvasMenu.eyedropper.size.5")), + Some(("11 by 11 Average", "canvasMenu.eyedropper.size.11")), + Some(("31 by 31 Average", "canvasMenu.eyedropper.size.31")), + Some(("51 by 51 Average", "canvasMenu.eyedropper.size.51")), + Some(("101 by 101 Average", "canvasMenu.eyedropper.size.101")), + None, + Some(("Copy Color as HTML", EYEDROPPER_COPY_HTML)), + Some(("Copy Color's Hex Code", EYEDROPPER_COPY_HEX)), +]; + +/// The Sample Size an Eyedropper menu row sets. +fn eyedropper_size(command: &str) -> Option { + command.strip_prefix("canvasMenu.eyedropper.size.")?.parse().ok() +} + +/// Is `menu` the Eyedropper's own menu (not the pasteboard, guide, transform or crop menu it can +/// also open)? +fn is_eyedropper(menu: &CanvasToolMenu) -> bool { + menu.tool == Tool::Eyedropper + && menu.crop.is_none() + && !menu.guide + && !menu.pasteboard + && !menu.transform + && menu.anchor.is_none() + && !menu.text + && !menu.type_layer +} + /// Photoshop's Pen context menu order. Rows whose operation is not applicable to the current /// path or layer stay visible and disabled. pub const PEN_MENU: &[Row] = &[ @@ -516,6 +566,8 @@ pub fn applies(tool: Tool) -> bool { // selection menu, as in Photoshop (#7268). | Tool::QuickSelection | Tool::ColorSampler + // Sample Size and Copy Color (#11747). + | Tool::Eyedropper ) || path_menu(tool) } @@ -558,7 +610,7 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { } else if menu.transform { TRANSFORM_MENU } else if menu.anchor.is_some() { - VIEW_MENU + if menu.tool == Tool::Hand { HAND_MENU } else { VIEW_MENU } } else if menu.text { TYPE_EDIT_MENU } else if menu.type_layer { @@ -567,6 +619,8 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { PEN_MENU } else if sampler_menu(menu) { SAMPLER_MENU + } else if menu.tool == Tool::Eyedropper { + EYEDROPPER_MENU } else { selection_rows(menu.has_selection) } @@ -593,6 +647,9 @@ pub(crate) fn mode_checked(app: &PhotocraftApp, menu: &CanvasToolMenu, command: if menu.text || menu.type_layer { return type_checked(app, command); } + if is_eyedropper(menu) { + return eyedropper_size(command) == Some(app.ui.tool_options.eyedropper_size); + } menu.transform && matches!(command, "edit.freeTransform" | "edit.transform.rotate" | "edit.transform.skew" | "edit.transform.distort" | "edit.transform.perspective") && app.ui.transform.as_ref().is_some_and(|t| t.mode == crate::state::TransformMode::for_command(command)) @@ -708,6 +765,7 @@ pub fn open_transform(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) -> crop: None, sampler: None, sampler_at: None, + color: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -791,6 +849,7 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: crop: None, sampler: None, sampler_at: None, + color: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -824,6 +883,7 @@ pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui crop: None, sampler: None, sampler_at: None, + color: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -858,6 +918,9 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) if menu.pasteboard { return PASTEBOARD_MENU.iter().flatten().any(|(_, id)| *id == command); } + if is_eyedropper(menu) { + return eyedropper_size(command).is_some() || (matches!(command, EYEDROPPER_COPY_HTML | EYEDROPPER_COPY_HEX) && menu.color.is_some()); + } // Warp needs a layer, selection or path box: a lone mask or channel keeps the plain box. if menu.transform && command == "edit.transform.warp" { return app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none() && t.target.is_none()); @@ -943,6 +1006,9 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] let spelling = if text { doc.and_then(|d| spelling_at(app, d)) } else { None }; let sampler = if tool == Tool::ColorSampler { doc.and_then(|d| crate::analysis_ui::sampler_at(app, d)) } else { None }; let sampler_at = sampler.and_then(|i| Some((app.session.active_index()?, *app.session.active()?.color_samplers.get(i)?))); + // The Eyedropper reads the colour now, under the right-click: all layers, with the Sample + // Size, whatever its Sample setting (#11747). Picking a row later copies this colour. + let color = if tool == Tool::Eyedropper && !text && !type_layer { doc.and_then(|d| crate::canvas::composite_color(app, d[0], d[1])) } else { None }; app.ui.canvas_tool_menu = Some(CanvasToolMenu { pos, tool, @@ -959,6 +1025,7 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] crop: None, sampler, sampler_at, + color, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -989,13 +1056,14 @@ pub fn open_view(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; crop: None, sampler: None, sampler_at: None, + color: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true } -/// A view menu row. Zoom In and Zoom Out step about the right-clicked point, as a Zoom tool click -/// does; the other rows run their View menu command. +/// A view menu row. The non-temporary Zoom tool's steps keep the view centre unless clicked-point +/// centring is enabled. Other view-tool cases retain their pressed-point anchoring. fn choose_view(app: &mut PhotocraftApp, ctx: &Context, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { let i = app.session.active_index().ok_or("no document")?; if command == FILL_SCREEN { @@ -1013,6 +1081,9 @@ fn choose_view(app: &mut PhotocraftApp, ctx: &Context, menu: &CanvasToolMenu, co } let (Some((zoom0, c)), Some(d)) = (before, menu.anchor) else { return Ok(()) }; let center_on_point = app.session.prefs().tools.zoom_clicked_point_to_center; + if menu.tool == Tool::Zoom && app.ui.tool == Tool::Zoom && app.ui.spring.is_none() && crate::hold_keys::held_tool(app, ctx).is_none() && !center_on_point { + return Ok(()); + } let Some(v) = app.ui.views.get_mut(i) else { return Ok(()) }; let d = [d[0] as f32, d[1] as f32]; // The view scales about the centre, so the point keeps its screen position when its offset @@ -1045,6 +1116,8 @@ pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) { } else if sampler_menu(&menu) { let (id, params) = engine_call(app, &menu, command); app.run(&id, params).map(|_| ()) + } else if is_eyedropper(&menu) { + choose_eyedropper(app, ctx, &menu, command) } else if command == "select.toWorkPath" { // Photoshop's Make Work Path… asks for the tolerance first. spec_dialog(app, command, "Make Work Path", r##"{"tolerance":0.5..10=2}"##, serde_json::Map::new()); @@ -1058,6 +1131,20 @@ pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) { } } +/// An Eyedropper row (#11747): a size sets the Sample Size (shared with the options bar); a Copy +/// Color row puts the colour read at the right-click on the clipboard, as the Color panel's menu +/// does. Neither touches the foreground colour or the history. +fn choose_eyedropper(app: &mut PhotocraftApp, ctx: &Context, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { + if let Some(size) = eyedropper_size(command) { + app.ui.tool_options.eyedropper_size = size; + return Ok(()); + } + let rgb = menu.color.ok_or("No colour under the pointer")?; + let text = if command == EYEDROPPER_COPY_HTML { crate::color_panel_ui::html_color(rgb) } else { crate::color_panel_ui::hex_code(rgb) }; + ctx.copy_text(text); + Ok(()) +} + /// A spelling row: replace the word under the pointer (the caret lands after the replacement), or /// add it to the user dictionary. fn choose_spelling(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { @@ -1303,8 +1390,27 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { choose(app, ctx, &command); } else if crate::canvas_popup::outside_pressed(ctx, id, area.response.rect) { app.ui.canvas_tool_menu = None; + // A fast click can press and release in one frame: the canvas input above already + // suppressed its action through the open-menu hit test, and the deferred release clear + // (in `canvas_view`, below the click handling) would never fire after this frame. Don't + // arm the flag then, or it would eat the next ordinary click (CodeRabbit, #9841). + app.ui.canvas_tool_menu_dismissed = !ctx.input(|i| i.pointer.any_released()); } } +/// Returns the menu rect if the canvas tool menu is currently open, for hit-testing +/// outside-click dismissal in the click handler. +pub fn menu_rect_if_open(app: &PhotocraftApp, ctx: &Context) -> Option { + let menu = app.ui.canvas_tool_menu.as_ref()?; + let id = menu_id(); + let screen = ctx.content_rect(); + let size = ctx.memory(|m| m.area_rect(id)).map_or(egui::vec2(210.0, 140.0), |r| r.size()); + let pos = egui::pos2(menu.pos[0].min(screen.right() - size.x).max(screen.left()), menu.pos[1].min(screen.bottom() - size.y).max(screen.top())); + Some(egui::Rect::from_min_size(pos, size)) +} + #[cfg(test)] mod tests; + +#[cfg(test)] +mod hand_menu_entries_tests; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/hand_menu_entries_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/hand_menu_entries_tests.rs new file mode 100644 index 0000000000..52424544c8 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/hand_menu_entries_tests.rs @@ -0,0 +1,63 @@ +//! #12022: the Hand tool's canvas right-click lists only Fit on Screen, 100%, 200% and Print Size; +//! the Zoom tool's menu is unchanged. + +use egui::Context; +use serde_json::json; + +use super::{FILL_SCREEN, HAND_MENU, Row, VIEW_MENU, choose, open_view, rows}; +use crate::PhotocraftApp; +use crate::state::Tool; + +fn labels(rows: &[Row]) -> Vec> { + rows.iter().map(|r| r.map(|(label, _)| label)).collect() +} + +/// A 400 × 300 document, optionally with everything selected, and the view menu of `tool` open. +fn menu_app(tool: Tool, selection: bool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + if selection { + app.run("select.all", json!({})).unwrap(); + } + app.sync_views(); + assert!(open_view(&mut app, &Context::default(), tool, [100.0, 100.0], [300.0, 100.0])); + app +} + +#[test] +fn the_hand_menu_lists_only_the_fixed_zooms() { + for selection in [false, true] { + let app = menu_app(Tool::Hand, selection); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert_eq!(labels(rows(&menu)), vec![Some("Fit on Screen"), Some("100%"), Some("200%"), Some("Print Size")], "selection {selection}"); + } +} + +#[test] +fn the_zoom_menu_is_unchanged() { + let app = menu_app(Tool::Zoom, false); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(rows(&menu) == VIEW_MENU); + assert_eq!( + labels(rows(&menu)), + vec![Some("Fit on Screen"), Some("Fill Screen"), Some("100%"), Some("200%"), Some("Print Size"), None, Some("Zoom In"), Some("Zoom Out")] + ); +} + +#[test] +fn the_hand_entries_zoom_and_add_no_history() { + let mut app = menu_app(Tool::Hand, false); + let before = app.session.active().unwrap().history.past_len(); + choose(&mut app, &Context::default(), "view.twoHundredPercent"); + assert_eq!(app.ui.views[0].zoom, 2.0); + assert_eq!(app.session.active().unwrap().history.past_len(), before); + // Rows that left the Hand's menu can't be run through it. + for gone in [FILL_SCREEN, "view.zoomIn", "view.zoomOut"] { + let mut app = menu_app(Tool::Hand, false); + let zoom = app.ui.views[0].zoom; + choose(&mut app, &Context::default(), gone); + assert_eq!(app.ui.views[0].zoom, zoom, "{gone}"); + assert!(!app.ui.views[0].fill_pending, "{gone}"); + } + assert!(HAND_MENU.iter().all(Option::is_some), "no separator"); +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs index e5c46b42ae..920767cb44 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -2,6 +2,9 @@ use super::*; use egui::{Modifiers, PointerButton, Pos2, vec2}; use egui_kittest::{Harness, kittest::Queryable}; +#[path = "zoom_menu_anchor_tests.rs"] +mod zoom_menu_anchor_tests; + fn app() -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); @@ -399,8 +402,8 @@ fn selection_menus_follow_photoshop_order() { Some("Save Selection…"), Some("Make Work Path…"), None, - Some("Layer via Copy"), - Some("Layer via Cut"), + Some("Layer Via Copy"), + Some("Layer Via Cut"), Some("New Layer…"), None, Some("Free Transform"), @@ -535,7 +538,8 @@ fn zoom_and_hand_right_click_opens_the_view_menu() { let inside = screen_of(h.state(), [300.0, 100.0]); right_click(&mut h, inside, Modifiers::NONE); let menu = h.state().ui.canvas_tool_menu.clone().unwrap_or_else(|| panic!("{tool:?}: right-click opens no menu")); - assert!(rows(&menu) == VIEW_MENU, "{tool:?}: the view menu"); + // The Hand's menu has only the fixed zooms (#12022). + assert!(rows(&menu) == if tool == Tool::Hand { HAND_MENU } else { VIEW_MENU }, "{tool:?}: the view menu"); assert_eq!(h.state().ui.views[0].zoom, zoom, "{tool:?}: the right-click alone does not zoom"); assert!(entry_enabled(h.state(), &menu, FILL_SCREEN) && entry_enabled(h.state(), &menu, "view.printSize")); // Outside the image the pasteboard colour menu wins, as for the other tools. @@ -546,12 +550,150 @@ fn zoom_and_hand_right_click_opens_the_view_menu() { } } +/// A zoom harness with a fixed camera: zoom 1.0 centred on the 400×300 document. `animated` is +/// Preferences › General › Animated Zoom; each step is 0.1 s of egui time, so a hold can pass +/// `zoom_hold::DELAY` within a few steps. +fn zoom_harness(animated: bool) -> Harness<'static, PhotocraftApp> { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Zoom; + app.run("prefs.set", json!({"values": {"general.animatedZoom": animated, "tools.zoomClickedPointToCenter": false, "tools.overscroll": true}})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).with_step_dt(0.1).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + let view = &mut h.state_mut().ui.views[0]; + view.zoom = 1.0; + view.center = [200.0, 150.0]; + view.fit_pending = false; + view.fill_pending = false; + h.run_steps(2); + h +} + +/// The menu opens at `[300, 100]` (doc points); this press lands 250 doc px to its left: outside +/// the 200 px-wide menu, on the canvas. +fn dismissal_point(h: &Harness<'static, PhotocraftApp>) -> Pos2 { + screen_of(h.state(), [50.0, 250.0]) +} + +/// #9832: a left press outside the open view menu dismisses it, and the whole gesture is +/// consumed — the press, the held press, and the release never zoom, and the next ordinary +/// click zooms again. #[test] -fn view_menu_zoom_in_keeps_the_clicked_point_under_the_pointer() { +fn dismissing_the_view_menu_consumes_the_whole_gesture() { + let mut h = zoom_harness(false); + let zoom = h.state().ui.views[0].zoom; + let open_at = screen_of(h.state(), [300.0, 100.0]); + right_click(&mut h, open_at, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some(), "right-click opens the view menu"); + // The dismissal press: the menu goes, the zoom does not. + let far = dismissal_point(&h); + h.event(egui::Event::PointerMoved(far)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the outside press dismisses the menu"); + assert_eq!(h.state().ui.views[0].zoom, zoom, "the dismissal press does not zoom"); + // Holding it (a long press releases as a click) still does nothing… + h.run_steps(2); + assert_eq!(h.state().ui.views[0].zoom, zoom, "a held dismissal press does not zoom"); + // …and the release over the canvas is consumed: no zoom step. + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().ui.views[0].zoom, zoom, "the dismissal release does not zoom"); + // The next ordinary click zooms again: the gesture flag did not stick. + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().ui.views[0].zoom, crate::zoom_levels::step(zoom, 1, h.state().ui.views[0].doc_size), "the next ordinary click zooms"); +} + +/// #9832: a menu-dismissal press held past `zoom_hold::DELAY` must not arm the animated zoom +/// hold: holding the dismissal click would otherwise zoom continuously. +#[test] +fn a_held_menu_dismissal_press_never_arms_the_zoom_hold() { + let mut h = zoom_harness(true); + let zoom = h.state().ui.views[0].zoom; + let open_at = screen_of(h.state(), [300.0, 100.0]); + right_click(&mut h, open_at, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some(), "right-click opens the view menu"); + let far = dismissal_point(&h); + h.event(egui::Event::PointerMoved(far)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the outside press dismisses the menu"); + // 0.8 s held still, well past the 0.3 s hold delay: every frame stays at the start zoom. + for i in 0..8 { + h.run_steps(1); + assert_eq!(h.state().ui.views[0].zoom, zoom, "held dismissal press frame {i} must not zoom"); + } + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().ui.views[0].zoom, zoom, "the dismissal release does not zoom either"); +} + +/// #9832 (CodeRabbit): while the dismissal press stays down, the temporary Hand (Space) and the +/// selected Hand must not pan either — the consumed gesture is inert until its release, and the +/// pans read `response.dragged()` directly, so they need the gate up front. +#[test] +fn a_held_menu_dismissal_press_cannot_pan_the_view() { + fn key(h: &mut Harness<'static, PhotocraftApp>, k: egui::Key, pressed: bool) { + h.event(egui::Event::Key { key: k, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + } + let mut h = zoom_harness(false); + let (zoom, center0) = (h.state().ui.views[0].zoom, h.state().ui.views[0].center); + let open_at = screen_of(h.state(), [300.0, 100.0]); + right_click(&mut h, open_at, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some(), "right-click opens the view menu"); + // The dismissal press: the menu goes, and the button stays down. + let far = dismissal_point(&h); + h.event(egui::Event::PointerMoved(far)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the outside press dismisses the menu"); + // Hold Space: the temporary Hand arms, but dragging must not pan the view. + key(&mut h, egui::Key::Space, true); + assert_eq!(crate::input::hold_keys::held_tool(h.state(), &h.ctx), Some(crate::input::hold_keys::Temporary::Hand), "Space arms the temporary hand"); + h.event(egui::Event::PointerMoved(far + vec2(120.0, -60.0))); + h.run_steps(2); + h.event(egui::Event::PointerMoved(far + vec2(240.0, -120.0))); + h.run_steps(2); + assert_eq!(h.state().ui.views[0].center, center0, "a held dismissal press must not pan the view"); + assert_eq!(h.state().ui.views[0].zoom, zoom); + // Release both: an ordinary Hand drag pans again, the flag did not stick. + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + key(&mut h, egui::Key::Space, false); + h.state_mut().ui.tool = Tool::Hand; + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(far + vec2(100.0, 50.0))); + h.run_steps(2); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_ne!(h.state().ui.views[0].center, center0, "an ordinary Hand drag pans the view again"); +} + +#[test] +fn view_menu_zoom_in_keeps_the_view_centre() { let mut app = zoom_app(400, 300); app.ui.tool = Tool::Zoom; let mut h = harness(app); let zoom = h.state().ui.views[0].zoom; + let center = h.state().ui.views[0].center; let doc = [300.0, 100.0]; let p = screen_of(h.state(), doc); right_click(&mut h, p, Modifiers::NONE); @@ -561,8 +703,7 @@ fn view_menu_zoom_in_keeps_the_clicked_point_under_the_pointer() { assert!(h.state().ui.canvas_tool_menu.is_none()); let after = h.state().ui.views[0].zoom; assert_eq!(after, crate::zoom_levels::step(zoom, 1, [400, 300]), "one Zoom In step"); - let s = screen_of(h.state(), doc); - assert!((s - p).length() < 1.0, "the right-clicked point stays put: {s:?} vs {p:?}"); + assert_eq!(h.state().ui.views[0].center, center); assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("view.zoomIn")); // Zoom Out returns to where it was. right_click(&mut h, p, Modifiers::NONE); @@ -573,12 +714,13 @@ fn view_menu_zoom_in_keeps_the_clicked_point_under_the_pointer() { } #[test] -fn animated_zoom_off_view_menu_keeps_the_anchor_without_a_transition() { +fn animated_zoom_off_view_menu_keeps_the_centre_without_a_transition() { for command in ["view.zoomIn", "view.zoomOut", FILL_SCREEN] { let mut app = zoom_app(400, 300); app.ui.tool = Tool::Zoom; app.run("prefs.set", json!({"values": {"general.animatedZoom": false, "tools.zoomClickedPointToCenter": false}})).unwrap(); let mut h = harness(app); + let center = h.state().ui.views[0].center; let doc = [300.0, 100.0]; let p = screen_of(h.state(), doc); right_click(&mut h, p, Modifiers::NONE); @@ -591,17 +733,18 @@ fn animated_zoom_off_view_menu_keeps_the_anchor_without_a_transition() { assert_eq!((xf.zoom, xf.center), (v.zoom, v.center), "{command}"); assert!(v.zoom_anchor.is_none() && v.zoom_transition.is_none(), "{command}"); if command != FILL_SCREEN { - assert!(screen_of(h.state(), doc).distance(p) < 1.0, "{command}: preserve the clicked point"); + assert_eq!(v.center, center, "{command}: preserve the view centre"); } } } #[test] -fn view_menu_zoom_keeps_its_anchor_during_the_animation() { +fn view_menu_zoom_keeps_its_centre_during_the_animation() { let mut app = zoom_app(400, 300); app.ui.tool = Tool::Zoom; let mut h = harness(app); let zoom = h.state().ui.views[0].zoom; + let center = h.state().ui.views[0].center; let doc = [300.0, 100.0]; let p = screen_of(h.state(), doc); right_click(&mut h, p, Modifiers::NONE); @@ -613,7 +756,7 @@ fn view_menu_zoom_keeps_its_anchor_during_the_animation() { h.step(); let displayed = crate::canvas::ViewXform::active(h.state()).unwrap(); assert!(displayed.zoom > zoom && displayed.zoom < h.state().ui.views[0].zoom); - assert!(displayed.to_screen(doc[0], doc[1]).distance(p) < 1.0); + assert!(displayed.to_screen(center[0], center[1]).distance(displayed.rect.center()) < 1.0); h.input_mut().time = Some(ctx.input(|i| i.time) + 0.3); h.step(); assert!(!h.state().ui.views[0].zoom_animating); @@ -622,7 +765,8 @@ fn view_menu_zoom_keeps_its_anchor_during_the_animation() { #[test] fn view_menu_zoom_in_centres_the_clicked_point_with_the_preference() { let mut app = zoom_app(400, 300); - app.ui.tool = Tool::Hand; + // Zoom In is on the Zoom tool's menu only (#12022). + app.ui.tool = Tool::Zoom; app.run("prefs.set", json!({"path": "tools.zoomClickedPointToCenter", "value": true})).unwrap(); let mut h = harness(app); let doc = [300.0, 100.0]; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/zoom_menu_anchor_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/zoom_menu_anchor_tests.rs new file mode 100644 index 0000000000..d5039a6257 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/zoom_menu_anchor_tests.rs @@ -0,0 +1,196 @@ +use super::*; + +#[test] +fn zoom_menu_steps_keep_the_view_centre_and_history() { + for animated in [false, true] { + for offset in [vec2(-160.0, -100.0), vec2(140.0, 80.0)] { + let mut app = zoom_app(2400, 1800); + app.ui.tool = Tool::Zoom; + app.run("prefs.set", json!({"values": {"general.animatedZoom": animated, "tools.zoomClickedPointToCenter": false}})).unwrap(); + let mut h = harness(app); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [928.0, 686.0]; + v.request_zoom_animation(false); + h.step(); + let center = h.state().ui.views[0].center; + let st = h.state().session.active().unwrap(); + let history = (st.history.past_len(), st.history.can_redo(), st.revision); + for (label, zoom) in [("Zoom In", 2.0), ("Zoom Out", 1.0), ("Zoom Out", 2.0 / 3.0)] { + let p = crate::canvas::ViewXform::active(h.state()).unwrap().rect.center() + offset; + right_click(&mut h, p, Modifiers::NONE); + h.get_by_label(label).click(); + h.run_steps(3); + let v = &h.state().ui.views[0]; + assert_eq!(v.zoom, zoom, "{label}: one ladder stop"); + assert_eq!(v.center, center, "{label}: the right-click must not move the view centre"); + let xf = crate::canvas::ViewXform::active(h.state()).unwrap(); + assert!(xf.to_screen(center[0], center[1]).distance(xf.rect.center()) < 1.0); + assert!(h.state().ui.canvas_tool_menu.is_none()); + let st = h.state().session.active().unwrap(); + assert_eq!((st.history.past_len(), st.history.can_redo(), st.revision), history); + } + } + } +} + +#[test] +fn clicked_point_zoom_keeps_its_anchor_and_hand_menu_rejects_step_commands() { + for (tool, center_on_point) in [(Tool::Zoom, true), (Tool::Hand, true), (Tool::Hand, false)] { + for (command, direction) in [("view.zoomIn", 1), ("view.zoomOut", -1)] { + let mut app = zoom_app(400, 300); + app.ui.tool = tool; + app.run("prefs.set", json!({"values": {"tools.zoomClickedPointToCenter": center_on_point, "tools.overscroll": true}})).unwrap(); + let mut h = harness(app); + let before = h.state().ui.views[0].clone(); + let p = screen_of(h.state(), [300.0, 100.0]); + right_click(&mut h, p, Modifiers::NONE); + let doc = h.state().ui.canvas_tool_menu.as_ref().unwrap().anchor.unwrap().map(|n| n as f32); + let ctx = h.ctx.clone(); + if tool == Tool::Hand { + // #12022 gives Hand only fixed zoom rows. An injected step command must not run. + assert!(!available(h.state(), h.state().ui.canvas_tool_menu.as_ref().unwrap(), command)); + choose(h.state_mut(), &ctx, command); + let v = &h.state().ui.views[0]; + assert_eq!((v.zoom, v.center), (before.zoom, before.center), "Hand must reject {command}"); + continue; + } + choose(h.state_mut(), &ctx, command); + let v = &h.state().ui.views[0]; + assert_eq!(v.zoom, crate::zoom_levels::step(before.zoom, direction, [400, 300])); + let expected = if center_on_point { doc } else { std::array::from_fn(|i| doc[i] - (doc[i] - before.center[i]) * before.zoom / v.zoom) }; + assert_eq!(v.center, expected, "{tool:?}: {command}"); + assert!(v.zoom_animating); + assert_eq!(v.zoom_anchor.is_some(), !center_on_point); + } + } +} + +#[test] +fn zoom_click_and_alt_click_still_anchor_at_the_pointer() { + for animated in [false, true] { + for (modifiers, direction) in [(Modifiers::NONE, 1), (Modifiers::ALT, -1)] { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Zoom; + app.run("prefs.set", json!({"values": {"general.animatedZoom": animated, "tools.zoomClickedPointToCenter": false, "tools.overscroll": true}})) + .unwrap(); + let mut h = harness(app); + let zoom = h.state().ui.views[0].zoom; + let doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + h.event(egui::Event::ModifiersChanged(modifiers)); + h.event(egui::Event::PointerMoved(p)); + h.step(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers }); + h.step(); + } + h.input_mut().time = Some(h.ctx.input(|i| i.time) + 0.3); + h.step(); + assert_eq!(h.state().ui.views[0].zoom, crate::zoom_levels::step(zoom, direction, [400, 300])); + assert!(screen_of(h.state(), doc).distance(p) < 1.0); + assert!(h.state().ui.canvas_tool_menu.is_none()); + assert_eq!(h.state().session.active().unwrap().history.past_len(), 0); + } + } +} + +#[test] +fn held_zoom_keys_still_open_no_view_menu() { + for tool in [Tool::Brush, Tool::Hand] { + for modifiers in [Modifiers::COMMAND, Modifiers::ALT] { + let mut app = zoom_app(400, 300); + app.ui.tool = tool; + let mut h = harness(app); + let modifiers = + Modifiers { mac_cmd: cfg!(target_os = "macos") && modifiers.command, ctrl: !cfg!(target_os = "macos") && modifiers.command, ..modifiers }; + h.event(egui::Event::ModifiersChanged(modifiers)); + h.event(egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed: true, repeat: false, modifiers }); + h.step(); + assert!(matches!(crate::hold_keys::held_tool(h.state(), &h.ctx), Some(crate::hold_keys::Temporary::ZoomIn | crate::hold_keys::Temporary::ZoomOut))); + let before = h.state().ui.views[0].clone(); + let p = screen_of(h.state(), [300.0, 100.0]); + right_click(&mut h, p, modifiers); + assert!(h.state().ui.canvas_tool_menu.is_none()); + assert_eq!(h.state().ui.tool, tool); + let v = &h.state().ui.views[0]; + assert_eq!((v.zoom, v.center), (before.zoom, before.center)); + } + } +} + +#[test] +fn held_zoom_with_zoom_selected_keeps_the_menu_pressed_point_anchor() { + for animated in [false, true] { + for (command, direction) in [("view.zoomIn", 1), ("view.zoomOut", -1)] { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Zoom; + app.run("prefs.set", json!({"values": {"general.animatedZoom": animated, "tools.zoomClickedPointToCenter": false, "tools.overscroll": true}})) + .unwrap(); + let mut h = harness(app); + h.event(egui::Event::ModifiersChanged(Modifiers::ALT)); + h.event(egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::ALT }); + h.step(); + assert_eq!(crate::hold_keys::held_tool(h.state(), &h.ctx), Some(crate::hold_keys::Temporary::ZoomOut)); + let zoom = h.state().ui.views[0].zoom; + let center = h.state().ui.views[0].center; + let doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + h.event(egui::Event::PointerMoved(p)); + h.step(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed, modifiers: Modifiers::ALT }); + h.step(); + } + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.tool == Tool::Zoom)); + assert_eq!(crate::hold_keys::held_tool(h.state(), &h.ctx), Some(crate::hold_keys::Temporary::ZoomOut)); + let ctx = h.ctx.clone(); + choose(h.state_mut(), &ctx, command); + assert_eq!(h.state().ui.views[0].zoom, crate::zoom_levels::step(zoom, direction, [400, 300])); + assert_ne!(h.state().ui.views[0].center, center, "{command}: preserve the held tool's pressed-point behavior"); + h.step(); + h.input_mut().time = Some(ctx.input(|i| i.time) + 0.11); + h.step(); + assert!(screen_of(h.state(), doc).distance(p) < 1.0, "{command}: anchor during animation"); + h.input_mut().time = Some(ctx.input(|i| i.time) + 0.3); + h.step(); + assert!(screen_of(h.state(), doc).distance(p) < 1.0, "{command}: settled anchor"); + assert_eq!(h.state().ui.tool, Tool::Zoom); + assert_eq!(h.state().session.active().unwrap().history.past_len(), 0); + } + } +} + +#[test] +fn held_z_menu_keeps_its_existing_pressed_point_anchor() { + for label in ["Zoom In", "Zoom Out"] { + let mut app = zoom_app(400, 300); + app.ui.tool = Tool::Brush; + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + h.event(egui::Event::Key { key: egui::Key::Z, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.step(); + assert_eq!(h.state().ui.tool, Tool::Zoom); + assert!(h.state().ui.spring.as_ref().is_some_and(|s| s.previous == Tool::Brush)); + let doc = [300.0, 100.0]; + let p = screen_of(h.state(), doc); + right_click(&mut h, p, Modifiers::NONE); + h.get_by_label(label).click(); + h.run_steps(3); + assert!(screen_of(h.state(), doc).distance(p) < 1.0, "{label}: a held Z keeps today's anchor"); + h.event(egui::Event::Key { key: egui::Key::Z, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert_eq!(h.state().ui.tool, Tool::Brush); + } +} diff --git a/crates/ui-egui/src/canvas/channel_view.rs b/crates/ui-egui/src/canvas/channel_view.rs index 6a15fb9bdd..163441252d 100644 --- a/crates/ui-egui/src/canvas/channel_view.rs +++ b/crates/ui-egui/src/canvas/channel_view.rs @@ -489,7 +489,7 @@ pub fn ensure(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, display: let st = app.session.documents().get(idx)?; let view = st.channel_view.clone(); let active = st.active_layer; - let (revision, last_damage) = (st.revision, st.last_damage); + let (revision, last_damage) = (st.revision, (st.damage_from(), st.last_damage)); let content = revision.wrapping_sub(st.view_revision); let id = st.doc.id.0; if view.is_plain(&st.doc) { diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index e4f0336b1d..44de2ec950 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -112,15 +112,16 @@ pub(super) fn eyedropper_ring(app: &mut PhotocraftApp, painter: &egui::Painter, const RING_GREY: Color32 = Color32::from_gray(127); /// Tools on which holding ⌥ (Alt) switches to the Eyedropper: a click or drag sets the -/// foreground colour, as with the Eyedropper itself (#417, the Background Eraser #11906). +/// foreground colour, as with the Eyedropper itself (#417, the Background Eraser #11906, the Color +/// Replacement tool #11914). pub(crate) fn alt_samples(tool: Tool, mods: egui::Modifiers) -> bool { // Control+Alt is the brush-resize drag (`brush_resize`), not sampling. - mods.alt && !mods.ctrl && matches!(tool, Tool::Brush | Tool::Pencil | Tool::Gradient | Tool::PaintBucket | Tool::BackgroundEraser) + mods.alt && !mods.ctrl && matches!(tool, Tool::Brush | Tool::Pencil | Tool::Gradient | Tool::PaintBucket | Tool::BackgroundEraser | Tool::ColorReplacement) } /// Preferences › Cursors › Other Cursors asks for the precise crosshair, or Caps Lock swaps the /// standard cursor for it (and back), as in Photoshop (#4639). -pub(super) fn precise_other_cursor(app: &PhotocraftApp) -> bool { +pub(crate) fn precise_other_cursor(app: &PhotocraftApp) -> bool { (app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise) != app.caps_lock } @@ -150,6 +151,20 @@ pub(crate) fn pipette_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon { egui::CursorIcon::None } +/// The filter dialogs' preview locator: a small square centred on `p`, the point a click centres +/// the dialog's preview window on (#9648), white between dark edges so it reads on any image. +/// Draws it at `p` and returns the OS cursor to set (hidden). +pub(crate) fn preview_locator_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon { + const SIDE: f32 = 9.0; + let rect = Rect::from_center_size(p, vec2(SIDE, SIDE)); + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("pc-preview-locator"))); + let dark = Stroke::new(1.0, Color32::from_black_alpha(200)); + painter.rect_stroke(rect.expand(1.0), 0.0, dark, egui::StrokeKind::Inside); + painter.rect_stroke(rect.shrink(1.0), 0.0, dark, egui::StrokeKind::Inside); + painter.rect_stroke(rect, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Inside); + egui::CursorIcon::None +} + /// The Paint Bucket artwork and target share one cached cursor image. Report rasterization /// failures once per distinct message, with the same concise error in the dialog and status bar. pub(crate) fn paint_bucket_cursor(app: &mut PhotocraftApp, painter: &egui::Painter, p: Pos2) -> egui::CursorIcon { @@ -290,6 +305,10 @@ pub(crate) fn alt_picks(tool: Tool, mods: egui::Modifiers) -> bool { #[path = "../eyedropper_mask_sample_tests.rs"] mod eyedropper_mask_sample_tests; +#[cfg(test)] +#[path = "../color_replacement_alt_click_tests.rs"] +mod color_replacement_alt_click_tests; + #[cfg(test)] #[path = "../background_eraser_alt_click_tests.rs"] mod background_eraser_alt_click_tests; diff --git a/crates/ui-egui/src/canvas/display.rs b/crates/ui-egui/src/canvas/display.rs index a171bd17bf..f9dfebc047 100644 --- a/crates/ui-egui/src/canvas/display.rs +++ b/crates/ui-egui/src/canvas/display.rs @@ -177,7 +177,7 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Ar && pv.doc.id == st.doc.id && st.doc.layer(photocraft_doc::LayerId(t.layer)).is_some() { - return (pv.doc.clone(), (1 << 40) + pv.session); + return (pv.doc.clone(), crate::transform_tool::preview_key(pv.session)); } // Layer Style dialog: show its effects live (Cancel just drops the preview). let style = app.ui.dialogs.iter().find(|d| d.kind == crate::state::DialogKind::LayerStyle); diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs index 54679f034d..641fa91720 100644 --- a/crates/ui-egui/src/canvas/filter_preview.rs +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -71,6 +71,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e command: cmd, params, k, + tool_colors: (app.session.tools.foreground, app.session.tools.background), }; let key = request.doc.0 ^ (1u64 << 61); // Every filter's preview computes off the UI thread in the desktop app: Gaussian Blur at @@ -128,6 +129,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e task.target, &documents, &color, + Some(task.tool_colors), ), } .map(|doc| { @@ -172,6 +174,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e request.target, &documents, &app.session.color.settings, + Some(request.tool_colors), ), } .map(|doc| { diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index b67aec4beb..32333e0388 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -133,18 +133,29 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option) { json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0, "mode": mode, "line": line, "antiAlias": false, "feather": feather}), ); } - Tool::Patch if crate::retouch_ui::patch_drags_selection(app, d.start, d.modifiers) => crate::retouch_ui::finish_patch(app, d.start, [end[0], end[1]]), + Tool::Patch if crate::retouch_ui::patch_drags_selection(app, d.start, d.modifiers) => { + crate::retouch_ui::finish_patch(app, d.start, crate::retouch_ui::patch_end(&d, [end[0], end[1]])) + } Tool::ContentAwareMove if crate::retouch_ui::patch_drags_selection(app, d.start, d.modifiers) => { crate::retouch_ui::finish_content_aware_move(app, d.start, [end[0], end[1]]) } Tool::Lasso | Tool::Patch | Tool::ContentAwareMove => { let pts: Vec<[f64; 2]> = d.points.iter().map(|p| [p[0], p[1]]).collect(); + // A Content-Aware Move drag with nothing to select only says so (#12192). + if d.tool == Tool::ContentAwareMove && crate::retouch_ui::content_aware_move_no_pixels(app, &pts) { + return; + } if pts.len() >= 3 { let mode = selection_mode(app, d.modifiers); let o = &app.ui.tool_options; // The Patch and Content-Aware Move tools have no Feather in their options bar. let feather = if d.tool == Tool::Lasso { o.feather } else { 0.0 }; - let made = app.run("select.lasso", json!({"points": pts, "mode": mode, "antiAlias": o.anti_alias, "feather": feather})); + let mut params = json!({"points": pts, "mode": mode, "antiAlias": o.anti_alias, "feather": feather}); + // The Patch tool's lasso is a step of that tool in History; the Lasso tool keeps "Lasso". + if d.tool == Tool::Patch { + params["historyName"] = json!("Patch Tool"); + } + let made = app.run("select.lasso", params); // The lasso only outlines the patch; say that it is dragged next (#1715). if made.is_ok() && d.tool != Tool::Lasso { crate::retouch_ui::patch_hint(app); diff --git a/crates/ui-egui/src/canvas/move_ui.rs b/crates/ui-egui/src/canvas/move_ui.rs index 0743905f7f..397037a6a1 100644 --- a/crates/ui-egui/src/canvas/move_ui.rs +++ b/crates/ui-egui/src/canvas/move_ui.rs @@ -223,6 +223,8 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc 0, "{depth}-bit: the mask sliding over the small layer changes pixels"); + } +} + /// Dragging with an unlinked mask targeted moves the mask alone, shown live and committed; /// with the mask linked (or the pixels targeted) the layer moves. #[test] diff --git a/crates/ui-egui/src/canvas/navigator.rs b/crates/ui-egui/src/canvas/navigator.rs index 413bf82686..c465a638bb 100644 --- a/crates/ui-egui/src/canvas/navigator.rs +++ b/crates/ui-egui/src/canvas/navigator.rs @@ -75,8 +75,8 @@ pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz return ensure_texture(app, ctx, idx, app.session.color.main_display).map(|(t, _)| t); } // Keyed by the document snapshot, not its revision: selecting a layer changes no pixels. - let (snapshot, id, revision, last_damage) = - app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id, st.revision, st.last_damage))?; + let (snapshot, id, revision, damage_from, last_damage) = + app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id, st.revision, st.damage_from(), st.last_damage))?; let (doc, preview_key) = display_doc(app, idx); let (display, display_key) = canvas_display(app, &doc, None); let preview_key = preview_key ^ display_key; @@ -102,13 +102,13 @@ pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz return Some(t.id()); } let t0 = crate::gpu_canvas::now_ms(); - // One edit since the cached image, with the area it changed: update just that part (nothing + // One edit (or command) since the cached image, with the area it changed: update just that part (nothing // for a rename, a selection or a new empty layer). A thumbnail composite of the whole // document on every edit cost a full-resolution CPU composite on the UI thread. let size = photocraft_compose::thumbnail_size(&doc, NAVIGATOR_SIDE); if let Some((_, p, rev, t)) = &cached && *p == preview_key - && rev.checked_add(1) == Some(revision) + && (damage_from..revision).contains(rev) && let Some(d) = last_damage && t.size() == [size.0 as usize, size.1 as usize] { diff --git a/crates/ui-egui/src/canvas/paint.rs b/crates/ui-egui/src/canvas/paint.rs index a091602313..7366dafdd3 100644 --- a/crates/ui-egui/src/canvas/paint.rs +++ b/crates/ui-egui/src/canvas/paint.rs @@ -660,7 +660,7 @@ pub(super) fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter // Patch / Content-Aware Move dragging the selection: its outline follows the pointer. Tool::Patch | Tool::ContentAwareMove if crate::retouch_ui::patch_drags_selection(app, d.start, d.modifiers) => { let start = d.start; - let [dx, dy] = crate::retouch_ui::patch_offset(app, start, last); + let [dx, dy] = crate::retouch_ui::patch_offset(app, start, crate::retouch_ui::patch_end(d, last)); if let Some((_, _, segs)) = &app.outline_cache { let moved: Vec = segs.iter().map(|(a, b)| ([a[0] + dx, a[1] + dy], [b[0] + dx, b[1] + dy])).collect(); marching_ants_segments(painter, xf, &moved, painter.ctx().input(|i| i.time)); diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index 2c16ce1fa1..fbf4e1ab0d 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -41,6 +41,9 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // in Normal mode: each tool's Mode starts at Normal, so a Multiply Brush doesn't make the // first Clone Stamp stroke multiply (or give Healing a mode its menu doesn't have). // The Art History Brush also starts at full opacity (#10263): its Opacity is its own. + // The Background Eraser and the Healing Brush start with their own measured tips instead, + // as the whole brush Reset Tool gives them (#11911, #12099). + None if matches!(tool, Tool::BackgroundEraser | Tool::Healing) => fresh_brush(tool, ¤t), None => { let opacity = if tool == Tool::ArtHistoryBrush { BrushSettings::default().opacity } else { current.opacity }; BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, opacity, ..current } @@ -70,14 +73,22 @@ fn session_fields(current: &BrushSettings, brush: &BrushSettings) -> BrushSettin /// The Brush tool's tip after Reset Tool, as the reference measures it (#11810): size, hardness /// and spacing of a 13 px soft round at 25 % spacing. const BRUSH_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); +/// The Background Eraser's tip after Reset Tool (#11911): a 13 px hard round at 25 % spacing. +const BACKGROUND_ERASER_TIP: (f32, f32, f32) = (13.0, 1.0, 0.25); +/// The Healing Brush's tip after Reset Tool (#12099): a 19 px hard round at 25 % spacing. +const HEALING_BRUSH_TIP: (f32, f32, f32) = (19.0, 1.0, 0.25); /// `tool`'s brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's /// smoothing, with the session's own fields of `current`. The Brush tool's tip is -/// [`BRUSH_TOOL_TIP`]; the other tools keep the default tip. +/// [`BRUSH_TOOL_TIP`], the Background Eraser's [`BACKGROUND_ERASER_TIP`], the Healing Brush's +/// [`HEALING_BRUSH_TIP`]; the other tools keep the default tip. pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings { let mut brush = BrushSettings { smoothing: first_smoothing(), ..BrushSettings::default() }; - if tool == Tool::Brush { - (brush.size, brush.hardness, brush.spacing) = BRUSH_TOOL_TIP; + match tool { + Tool::Brush => (brush.size, brush.hardness, brush.spacing) = BRUSH_TOOL_TIP, + Tool::BackgroundEraser => (brush.size, brush.hardness, brush.spacing) = BACKGROUND_ERASER_TIP, + Tool::Healing => (brush.size, brush.hardness, brush.spacing) = HEALING_BRUSH_TIP, + _ => {} } session_fields(current, &brush) } @@ -348,7 +359,8 @@ pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool) // ⌘/Ctrl+right-click lists the layers under the pointer instead (layer_pick_ui.rs, #307). let layer_menu = crate::layer_pick_ui::is_gesture(tool, mods); // Decided by the modifiers held when the button went down, not by those of the release frame that reports the click. - let mode_menu = crate::brush_mode_menu::is_gesture(tool, crate::workspace_ui::sticky_mods(app, crate::brush_mode_menu::gesture_mods(&response.ctx, mods))); + let mode_menu = + crate::brush_mode_menu::opens_on(app, tool, crate::workspace_ui::sticky_mods(app, crate::brush_mode_menu::gesture_mods(&response.ctx, mods))); if mode_menu && !resizing && app.drag.is_none() { app.secondary_erase = false; if let Some(p) = right_click_at(response) { @@ -425,7 +437,7 @@ pub fn pointer_secondary(app: &mut PhotocraftApp, ctx: &egui::Context, down: boo app.brush_resize_armed = down && app.drag.is_none(); return true; } - if crate::brush_mode_menu::is_gesture(tool, mods) && app.drag.is_none() && app.brush_resize.is_none() { + if crate::brush_mode_menu::opens_on(app, tool, mods) && app.drag.is_none() && app.brush_resize.is_none() { app.secondary_erase = false; if down { crate::brush_mode_menu::open(app, ctx, at); @@ -481,8 +493,15 @@ pub fn show_picker(app: &mut PhotocraftApp, ctx: &egui::Context) { let before = app.session.tools.brush.clone(); let mut b = before.clone(); let list = &mut app.ui.brush_picker_list; - let frame = egui::Frame::popup(ui.style()) - .show(ui, |ui| crate::brush_picker::body(ui, &mut b, &app.session.tools.presets, app.session.tools.current_preset.as_deref(), list, content)); + let frame = egui::Frame::popup(ui.style()).show(ui, |ui| { + // The Background Eraser has its own compact popup, without presets (#11910). + if app.ui.tool == Tool::BackgroundEraser { + crate::bg_eraser_popup::body(ui, &mut b, &mut app.ui.tool_options.bg_tolerance_control); + Vec::new() + } else { + crate::brush_picker::body(ui, &mut b, &app.session.tools.presets, app.session.tools.current_preset.as_deref(), list, content) + } + }); let picks = frame.inner; // The corner grip resizes the picker, and the size is remembered across opens. if let Some(new) = crate::brush_picker::resize_grip(ui, frame.response.rect, content) { diff --git a/crates/ui-egui/src/canvas/paint_mouse/tests.rs b/crates/ui-egui/src/canvas/paint_mouse/tests.rs index c31e137e82..8880183d29 100644 --- a/crates/ui-egui/src/canvas/paint_mouse/tests.rs +++ b/crates/ui-egui/src/canvas/paint_mouse/tests.rs @@ -423,11 +423,15 @@ fn picker_gear_menu_saves_and_names_a_new_preset() { assert_eq!(h.state().session.tools.current_preset.as_deref(), Some("Inky")); h.state_mut().ui.brush_picker = Some([c.x, c.y]); h.run_steps(2); - // The gear's boxes pick the card parts; the last one on can't be turned off. + // The gear's boxes pick the card parts; the last one on can't be turned off. Brush Tip + // starts off (#11819). h.get_by_label("Brush Preset Options").click(); h.run_steps(2); h.get_by_label("Brush Tip").click(); h.run_steps(2); + assert!(h.state().ui.brush_picker_list.show_tip); + h.get_by_label("Brush Tip").click(); + h.run_steps(2); assert!(!h.state().ui.brush_picker_list.show_tip); h.get_by_label("Brush Stroke").click(); h.run_steps(2); @@ -1023,3 +1027,59 @@ fn a_right_click_moved_and_released_in_one_frame_still_opens_its_menu() { assert_eq!(h.state().ui.brush_picker, None); assert_eq!(h.state().ui.canvas_tool_menu, None); } + +/// #11897: Clear chosen on a pixel layer, then the Background activated: a Brush stroke there +/// paints the foreground, and the Mode reads Normal afterwards. +#[test] +fn chosen_clear_paints_normally_on_the_background_and_the_mode_reads_normal() { + let mut h = harness(None); + h.state_mut().ui.tool_options.brush_clear = true; + let bg = h.state().session.active().unwrap().doc.background().unwrap().id; + h.state_mut().run("layer.select", json!({"layer": bg.0})).unwrap(); + h.run_steps(2); + let (a, b) = drag(&mut h, PointerButton::Primary); + assert!(!h.state().ui.tool_options.brush_clear, "the Mode reads Normal"); + let last = strokes(&h).last().cloned().unwrap(); + assert!(last.get("mode").is_none() && !last["erase"].as_bool().unwrap(), "{last}"); + let app = h.state(); + let v = app.ui.views[0].clone(); + let d = ((a + (b - a) * 0.5) - app.last_canvas_rect.center()) / v.zoom; + let st = app.session.active().unwrap(); + let px = st.doc.layer(bg).unwrap().surface().unwrap().rgba((d.x + v.center[0]) as i32, (d.y + v.center[1]) as i32); + assert!(px[2] > 0.9 && px[0] < 0.1, "the foreground blue, not the background colour: {px:?}"); +} + +/// #11897: a Background with Lock All refuses the stroke, so a chosen Clear stays chosen. +#[test] +fn chosen_clear_stays_on_a_locked_background() { + let mut h = harness(None); + h.state_mut().ui.tool_options.brush_clear = true; + let bg = h.state().session.active().unwrap().doc.background().unwrap().id; + h.state_mut().run("layer.select", json!({"layer": bg.0})).unwrap(); + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + h.run_steps(2); + drag(&mut h, PointerButton::Primary); + assert!(h.state().ui.tool_options.brush_clear, "the Mode still reads Clear"); +} + +/// #11897: a held `~` on the Background keeps erasing to the background colour. +#[test] +fn held_tilde_on_the_background_paints_the_background_colour() { + let mut h = harness(None); + h.state_mut().run("tools.setColors", json!({"background": "#00ff00"})).unwrap(); + let bg = h.state().session.active().unwrap().doc.background().unwrap().id; + h.state_mut().run("layer.select", json!({"layer": bg.0})).unwrap(); + h.run_steps(2); + h.event(egui::Event::Key { key: egui::Key::Backtick, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + let (a, b) = drag(&mut h, PointerButton::Primary); + h.event(egui::Event::Key { key: egui::Key::Backtick, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert_eq!(strokes(&h).last().unwrap()["mode"], json!("clear")); + let app = h.state(); + let v = app.ui.views[0].clone(); + let d = ((a + (b - a) * 0.5) - app.last_canvas_rect.center()) / v.zoom; + let st = app.session.active().unwrap(); + let px = st.doc.layer(bg).unwrap().surface().unwrap().rgba((d.x + v.center[0]) as i32, (d.y + v.center[1]) as i32); + assert!(px[1] > 0.9 && px[0] < 0.1 && px[2] < 0.1, "the background green, not the foreground blue: {px:?}"); +} diff --git a/crates/ui-egui/src/canvas/patch_preview.rs b/crates/ui-egui/src/canvas/patch_preview.rs index b669a60ed3..942acc4da4 100644 --- a/crates/ui-egui/src/canvas/patch_preview.rs +++ b/crates/ui-egui/src/canvas/patch_preview.rs @@ -30,14 +30,14 @@ pub(crate) struct PatchPreview { } /// The offset of the current Patch drag, if one is dragging the patch (not drawing a lasso). -fn drag_offset(app: &mut PhotocraftApp) -> Option<[i32; 2]> { +pub(crate) fn drag_offset(app: &mut PhotocraftApp) -> Option<[i32; 2]> { // Content-Aware patches are background jobs: the canvas shows the result when it is done. if app.ui.tool_options.patch_content_aware { return None; } let d = app.drag.as_ref().filter(|d| d.tool == Tool::Patch)?; let (start, mods) = (d.start, d.modifiers); - let end = d.points.last().map_or(start, |p| [p[0], p[1]]); + let end = crate::retouch_ui::patch_end(d, d.points.last().map_or(start, |p| [p[0], p[1]])); if !crate::retouch_ui::patch_drags_selection(app, start, mods) { return None; } diff --git a/crates/ui-egui/src/canvas/scroll_all_windows.rs b/crates/ui-egui/src/canvas/scroll_all_windows.rs new file mode 100644 index 0000000000..97e2537003 --- /dev/null +++ b/crates/ui-egui/src/canvas/scroll_all_windows.rs @@ -0,0 +1,569 @@ +//! Hand tool › Scroll All Windows. +//! +//! With the option on, or with Shift held while dragging with the Hand, a drag in one document +//! view scrolls every other view that is shown: the main window's document, or the documents in its +//! Window › Arrange tiles, and the document windows of Float in Window and New Window for Document. +//! After each step of the drag, each of those views moves by the same distance in document pixels +//! as the dragged view, as the reference application does: a view at 100 % moves twice the screen +//! distance of one at 50 %. Each view keeps its own zoom and rotation. Documents in hidden tabs +//! keep their views. + +use crate::PhotocraftApp; +use crate::state::View; + +/// The view a Hand drag moves itself: a document's view in the main window, or a document window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Source { + Main(usize), + Window(u64), +} + +/// The view that the canvas of document `idx` being drawn shows: the document window +/// `canvas::extra_windows` is drawing, or else the document's view in the main window. +pub fn source(app: &PhotocraftApp, idx: usize) -> Source { + app.drawing_window.map_or(Source::Main(idx), Source::Window) +} + +/// Whether a Hand drag scrolls every shown view: Scroll All Windows is on, or Shift is held. +pub fn active(app: &PhotocraftApp, shift: bool) -> bool { + app.ui.tool_options.hand_scroll_all || shift +} + +/// Store `scroll_all` under `id` while the Hand is dragging, and return the stored choice: a glide +/// after the drag keeps the choice the drag made. +pub fn glide_choice(ctx: &egui::Context, id: egui::Id, dragging: bool, scroll_all: bool) -> bool { + if dragging { + ctx.data_mut(|m| m.insert_temp(id, scroll_all)); + } + ctx.data(|m| m.get_temp::(id)).unwrap_or(false) +} + +/// Canvas geometry used to clamp a Hand drag when Overscroll is off. +pub struct ClampGeometry { + pub size: egui::Vec2, + pub ppp: f32, + pub aspect: f32, +} + +/// Move the other shown views after one step of a Hand drag or glide, which moved the dragged view's +/// center from `before` to `view.center`. With Overscroll off, both centers are taken where the +/// dragged view is clamped to, so a view held at its pan limit moves the others no further. +pub fn follow_step(app: &mut PhotocraftApp, enabled: bool, source: Source, before: [f32; 2], view: &View, geometry: ClampGeometry) { + if !enabled { + return; + } + let mut from = View { center: before, ..view.clone() }; + let mut to = view.clone(); + if !app.session.prefs().tools.overscroll { + crate::scrollbars::clamp_view_with_aspect(&mut from, geometry.size, geometry.ppp, geometry.aspect); + crate::scrollbars::clamp_view_with_aspect(&mut to, geometry.size, geometry.ppp, geometry.aspect); + } + follow(app, source, [to.center[0] - from.center[0], to.center[1] - from.center[1]]); +} + +/// Whether the main window shows the Home screen or an open-file card instead of a document +/// canvas, as `tabs::documents` draws it. +fn main_canvas_hidden(app: &mut PhotocraftApp) -> bool { + let n = app.session.documents().len(); + let opening = !app.jobs.opens.is_empty(); + (!opening && app.ui.chrome.shows_home(n, app.session.prefs().general.auto_show_home_screen)) || app.jobs.focus.is_some() +} + +/// Move every shown view except `source` by `delta`, a distance in document pixels: each view's +/// center moves by the same number of its own document's pixels. +pub fn follow(app: &mut PhotocraftApp, source: Source, delta: [f32; 2]) { + if !(delta[0].is_finite() && delta[1].is_finite()) || delta == [0.0, 0.0] { + return; + } + let place = |v: &mut View| { + let c = [v.center[0] + delta[0], v.center[1] + delta[1]]; + if c[0].is_finite() && c[1].is_finite() { + v.zoom_animating = false; + v.zoom_anchor = None; + v.fit_pending = false; + v.fill_pending = false; + v.center = c; + } + }; + if !main_canvas_hidden(app) { + // The main window shows the arranged tiles, or else a docked document alone. + let shown: Vec = match crate::canvas::arranged_cells(app, app.last_canvas_rect) { + Some(cells) => cells.into_iter().map(|(d, _)| d).collect(), + None => super::tabs::main_canvas_document(app).into_iter().collect(), + }; + for d in shown { + if source != Source::Main(d) + && let Some(v) = app.ui.views.get_mut(d) + { + place(v); + } + } + } + for w in app.ui.windows.iter_mut().filter(|w| w.open && source != Source::Window(w.id)) { + place(&mut w.view); + } +} + +#[cfg(test)] +mod tests { + use egui::{Pos2, Rect, vec2}; + use serde_json::json; + + use super::*; + use crate::state::{DocWindow, Tool}; + + fn view(zoom: f32, center: [f32; 2], rotation: f32) -> View { + View { zoom, center, rotation, fit_pending: false, fill_pending: false, ..View::default() } + } + + /// Three documents of different sizes, the first two tiled side by side and the third in a + /// hidden tab. + fn app_with_tiles() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + for (w, h) in [(400, 300), (800, 600), (200, 100)] { + app.run("file.new", json!({"width": w, "height": h})).unwrap(); + } + app.sync_views(); + app.session.set_active(0); + app.ui.view.arrange = "twoUpVertical".into(); + app.arrange_start = 0; + app.ui.views[0] = view(1.0, [200.0, 150.0], 0.0); + app.ui.views[1] = view(2.0, [400.0, 300.0], 0.0); + app.ui.views[2] = view(1.0, [100.0, 50.0], 0.0); + app + } + + fn near(a: [f32; 2], b: [f32; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-3 && (a[1] - b[1]).abs() < 1e-3 + } + + #[test] + fn a_drag_moves_the_other_shown_views_by_the_same_document_pixel_distance() { + let mut app = app_with_tiles(); + app.ui.windows.push(DocWindow { + id: 7, + document: 2, + view: view(0.5, [100.0, 50.0], 90.0), + open: true, + floating: false, + focused: false, + position: None, + }); + // The dragged 400 × 300 view's center moved 50 document pixels left and 20 down. + follow(&mut app, Source::Main(0), [-50.0, 20.0]); + assert_eq!(app.ui.views[0].center, [200.0, 150.0], "the dragged view's canvas stores its own view"); + // The 800 × 600 tile at 200 % moves by the same document pixels, not to the same fraction. + assert!(near(app.ui.views[1].center, [350.0, 320.0]), "{:?}", app.ui.views[1].center); + assert_eq!(app.ui.views[1].zoom, 2.0, "each view keeps its zoom"); + // The document window shows the 200 × 100 document at 50 %, turned 90°. + let w = &app.ui.windows[0].view; + assert!(near(w.center, [50.0, 70.0]), "{:?}", w.center); + assert_eq!((w.zoom, w.rotation), (0.5, 90.0), "and its rotation"); + // The third document's main view is in a tab hidden behind the tiles: it stays. + assert_eq!(app.ui.views[2].center, [100.0, 50.0]); + } + + #[test] + fn a_drag_in_a_document_window_scrolls_the_main_window_and_skips_itself() { + let mut app = app_with_tiles(); + app.ui.view.arrange = String::new(); + app.ui.windows.push(DocWindow { + id: 3, + document: 1, + view: view(1.0, [400.0, 300.0], 0.0), + open: true, + floating: false, + focused: false, + position: None, + }); + app.ui.windows.push(DocWindow { + id: 4, + document: 2, + view: view(1.0, [100.0, 50.0], 0.0), + open: false, + floating: false, + focused: false, + position: None, + }); + // The window's 800 × 600 view moved its center 100 document pixels right and 75 up. + follow(&mut app, Source::Window(3), [100.0, -75.0]); + assert_eq!(app.ui.windows[0].view.center, [400.0, 300.0], "the dragged window's canvas stores its own view"); + // Tabs: the main window shows the active 400 × 300 document only. + assert!(near(app.ui.views[0].center, [300.0, 75.0]), "{:?}", app.ui.views[0].center); + assert_eq!(app.ui.views[1].center, [400.0, 300.0], "a hidden tab stays"); + assert_eq!(app.ui.windows[1].view.center, [100.0, 50.0], "a closed window stays"); + } + + #[test] + fn a_drag_in_a_floated_document_scrolls_the_visible_docked_document() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.session.set_active(0); + app.ui.views[0] = view(1.0, [200.0, 150.0], 0.0); + app.ui.views[1] = view(1.0, [400.0, 300.0], 0.0); + crate::menus::invoke(&mut app, &egui::Context::default(), "window.arrange.floatInWindow", json!({"document": 0})).unwrap(); + assert!(app.ui.windows[0].floating); + assert_eq!(app.session.active_index(), Some(0)); + assert_eq!(super::super::main_canvas_document(&app), Some(1)); + let window_id = app.ui.windows[0].id; + + // The floated 400 × 300 view moved 100 document pixels left and 90 up. + follow(&mut app, Source::Window(window_id), [-100.0, -90.0]); + assert!(near(app.ui.views[1].center, [300.0, 210.0]), "{:?}", app.ui.views[1].center); + assert_eq!(app.ui.views[0].center, [200.0, 150.0], "the floated document's hidden main view stays"); + } + + #[test] + fn a_drag_in_a_document_window_skips_the_main_view_behind_home_or_an_open_card() { + for home in [true, false] { + let mut app = app_with_tiles(); + app.ui.view.arrange.clear(); + app.ui.windows.push(DocWindow { + id: 3, + document: 1, + view: view(1.0, [400.0, 300.0], 0.0), + open: true, + floating: false, + focused: false, + position: None, + }); + app.ui.windows.push(DocWindow { + id: 4, + document: 2, + view: view(1.0, [100.0, 50.0], 0.0), + open: true, + floating: false, + focused: false, + position: None, + }); + if home { + app.ui.chrome.home = Some(app.session.documents().len()); + } else { + let job = photocraft_engine::jobs::JobId(9); + app.jobs.opens.push(crate::jobs_ui::OpenTab { job, name: "opening.psd".into(), path: None, slot: None, order: None }); + app.jobs.focus = Some(job); + } + + follow(&mut app, Source::Window(3), [-30.0, -10.0]); + assert_eq!(app.ui.views[0].center, [200.0, 150.0], "the main canvas is hidden when home={home}"); + assert!(near(app.ui.windows[1].view.center, [70.0, 40.0]), "another document window follows when home={home}"); + } + } + + #[test] + fn the_source_is_the_document_window_being_drawn() { + let mut app = app_with_tiles(); + assert_eq!(source(&app, 1), Source::Main(1)); + app.drawing_window = Some(9); + assert_eq!(source(&app, 1), Source::Window(9)); + } + + /// A Hand drag with `option` and the Shift key as given, on the main canvas of the 2000 × 1500 + /// document 0 or (`in_window`) on the canvas of a window showing the 1000 × 750 document 1, as + /// `canvas::extra_windows` draws it. Both views start at their document's center, the main view + /// at 100 % and the window at 50 %. + /// Returns the dragged view's center and the stored centers of document 0's main view and of + /// the window's view. + fn drag_on_canvas(option: bool, shift: bool, in_window: bool) -> ([f32; 2], [f32; 2], [f32; 2]) { + drag_on_canvas_with(option, shift, false, in_window, false) + } + + /// As `drag_on_canvas`, with Shift held in Window › Modifier Keys when `sticky_shift` is set, + /// and with a dialog open over the canvas when `dialog` is set. + fn drag_on_canvas_with(option: bool, shift: bool, sticky_shift: bool, in_window: bool, dialog: bool) -> ([f32; 2], [f32; 2], [f32; 2]) { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 2000, "height": 1500})).unwrap(); + app.run("file.new", json!({"width": 1000, "height": 750})).unwrap(); + app.run("prefs.set", json!({"path": "tools.enableFlickPanning", "value": false})).unwrap(); + app.sync_views(); + app.session.set_active(0); + app.ui.tool = Tool::Hand; + app.ui.tool_options.hand_scroll_all = option; + app.ui.shell.sticky_shift = sticky_shift; + if dialog { + app.ui.open_dialog(crate::state::DialogKind::About, Default::default()); + } + app.ui.views[0] = view(1.0, [1000.0, 750.0], 0.0); + app.ui.windows.push(DocWindow { + id: 5, + document: 1, + view: view(0.5, [500.0, 375.0], 0.0), + open: true, + floating: false, + focused: false, + position: None, + }); + let mut v = if in_window { view(0.5, [500.0, 375.0], 0.0) } else { view(1.0, [1000.0, 750.0], 0.0) }; + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let modifiers = if shift { egui::Modifiers::SHIFT } else { egui::Modifiers::NONE }; + let mut frame = |app: &mut PhotocraftApp, events: Vec| { + let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + // The open dialog's modal layer leaves the canvas widget inert (`dialogs::pan_delta`). + if dialog { + ui.disable(); + } + if in_window { + app.drawing_window = Some(5); + v = crate::canvas::canvas_view(app, ui, 1, rect, v.clone(), false); + app.drawing_window = None; + } else { + v = crate::canvas::canvas_view(app, ui, 0, rect, v.clone(), true); + } + }); + out.textures_delta.clear(); + }; + let start = Pos2::new(200.0, 150.0); + let press = |pos: Pos2, pressed: bool| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + frame(&mut app, vec![egui::Event::ModifiersChanged(modifiers), egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true)]); + let end = start + vec2(-60.0, 30.0); + for i in 1..=6 { + frame(&mut app, vec![egui::Event::PointerMoved(start + (end - start) * (i as f32 / 6.0))]); + } + frame(&mut app, vec![press(end, false)]); + (v.center, app.ui.views[0].center, app.ui.windows[0].view.center) + } + + #[test] + fn the_option_or_shift_makes_a_hand_drag_scroll_the_document_windows_too() { + let (dragged, _, window) = drag_on_canvas(false, false, false); + assert!(near(dragged, [1060.0, 720.0]), "the dragged view follows the pointer: {dragged:?}"); + assert_eq!(window, [500.0, 375.0], "off: the window stays"); + // The same 60 and -30 document pixels in the window at 50 %: half the screen distance. + let moved = [560.0, 345.0]; + let (_, _, window) = drag_on_canvas(true, false, false); + assert!(near(window, moved), "on: it moves by the same document pixels: {window:?}"); + let (_, _, window) = drag_on_canvas(false, true, false); + assert!(near(window, moved), "Shift turns it on for the drag: {window:?}"); + } + + #[test] + fn shift_held_in_the_modifier_keys_panel_makes_a_hand_drag_scroll_the_document_windows_too() { + let (dragged, _, window) = drag_on_canvas_with(false, false, true, false, false); + assert!(near(dragged, [1060.0, 720.0]), "the dragged view follows the pointer: {dragged:?}"); + assert!(near(window, [560.0, 345.0]), "sticky Shift turns it on for the drag: {window:?}"); + } + + #[test] + fn a_hand_drag_under_an_open_dialog_scrolls_the_document_windows_too() { + let (dragged, _, window) = drag_on_canvas_with(false, false, false, false, true); + assert!(near(dragged, [1060.0, 720.0]), "the dragged view pans under the dialog: {dragged:?}"); + assert_eq!(window, [500.0, 375.0], "off: the window stays"); + let (_, _, window) = drag_on_canvas_with(true, false, false, false, true); + assert!(near(window, [560.0, 345.0]), "on: it moves by the same document pixels: {window:?}"); + let (_, _, window) = drag_on_canvas_with(false, true, false, false, true); + assert!(near(window, [560.0, 345.0]), "Shift turns it on for the drag: {window:?}"); + } + + #[test] + fn a_hand_drag_in_a_document_window_scrolls_the_main_window_once() { + let (dragged, main, window) = drag_on_canvas(false, false, true); + // At 50 % the window's center moves twice the screen distance in document pixels. + assert!(near(dragged, [620.0, 315.0]), "the dragged window follows the pointer: {dragged:?}"); + assert_eq!((main, window), ([1000.0, 750.0], [500.0, 375.0]), "off: nothing else moves"); + // The window's own canvas moved its view (`dragged`), and `follow` leaves its stored view + // alone: `extra_windows` stores the canvas's view, so the window moves once. + let (dragged, main, window) = drag_on_canvas(true, false, true); + assert!(near(dragged, [620.0, 315.0]), "{dragged:?}"); + // The main view at 100 % moves the same 120 and -60 document pixels: twice the screen distance. + assert!(near(main, [1120.0, 690.0]), "on: the main window moves by the same document pixels: {main:?}"); + assert_eq!(window, [500.0, 375.0]); + } + + #[test] + fn with_overscroll_off_the_other_windows_follow_the_clamped_center() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 2000, "height": 1500})).unwrap(); + app.run("file.new", json!({"width": 1000, "height": 750})).unwrap(); + app.run("prefs.set", json!({"values": {"tools.enableFlickPanning": false, "tools.overscroll": false}})).unwrap(); + app.sync_views(); + app.session.set_active(0); + app.ui.tool = Tool::Hand; + app.ui.tool_options.hand_scroll_all = true; + app.ui.windows.push(DocWindow { + id: 5, + document: 1, + view: view(4.0, [500.0, 375.0], 0.0), + open: true, + floating: false, + focused: false, + position: None, + }); + // A 400 × 300 canvas at 100 % keeps the center 200 px or more inside the left edge. + let mut v = view(1.0, [220.0, 750.0], 0.0); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let mut frame = |app: &mut PhotocraftApp, events: Vec| { + let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + v = crate::canvas::canvas_view(app, ui, 0, rect, v.clone(), true); + }); + out.textures_delta.clear(); + }; + let start = Pos2::new(200.0, 150.0); + let press = + |pos: Pos2, pressed: bool| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut app, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true)]); + let end = start + vec2(60.0, 0.0); + for i in 1..=6 { + frame(&mut app, vec![egui::Event::PointerMoved(start + (end - start) * (i as f32 / 6.0))]); + } + frame(&mut app, vec![press(end, false)]); + frame(&mut app, vec![]); + assert!(near(v.center, [200.0, 750.0]), "the dragged view stops at its limit: {:?}", v.center); + // The dragged view moved 20 document pixels before its limit held it; the window moves the + // same 20, not the 60 of the pointer, though at 400 % it has room to go further left. + let window = app.ui.windows[0].view.center; + assert!(near(window, [480.0, 375.0]), "{window:?}"); + } + + #[test] + fn a_flick_panning_glide_moves_the_other_windows_too() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 2000, "height": 1500})).unwrap(); + app.run("file.new", json!({"width": 1000, "height": 750})).unwrap(); + app.run("prefs.set", json!({"path": "tools.enableFlickPanning", "value": true})).unwrap(); + app.sync_views(); + app.session.set_active(0); + app.ui.tool = Tool::Hand; + app.ui.windows.push(DocWindow { + id: 5, + document: 1, + view: view(1.0, [500.0, 375.0], 0.0), + open: true, + floating: false, + focused: false, + position: None, + }); + let mut v = view(1.0, [1000.0, 750.0], 0.0); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let mut frame = |app: &mut PhotocraftApp, events: Vec| -> [f32; 2] { + let input = egui::RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + v = crate::canvas::canvas_view(app, ui, 0, rect, v.clone(), true); + }); + out.textures_delta.clear(); + v.center + }; + let start = Pos2::new(200.0, 150.0); + let press = + |pos: Pos2, pressed: bool| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + // Shift turns Scroll All Windows on for the drag, and is let go with the button. + frame(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), egui::Event::PointerMoved(start)]); + frame(&mut app, vec![press(start, true)]); + let mut end = start; + for i in 1..=8 { + end = start + vec2(-20.0 * i as f32, 0.0); + frame(&mut app, vec![egui::Event::PointerMoved(end)]); + } + let released = frame(&mut app, vec![press(end, false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + // On each frame of the glide the window has moved by the same document pixels as the + // dragged view, though its document is half the size. + let mut glided = released; + for _ in 0..5 { + glided = frame(&mut app, vec![]); + let same = [glided[0] - 500.0, glided[1] - 375.0]; + assert!(near(app.ui.windows[0].view.center, same), "{:?} {same:?}", app.ui.windows[0].view.center); + } + assert!(glided[0] > released[0], "the dragged view glides on: {released:?} {glided:?}"); + } + + #[test] + fn the_hand_tool_options_bar_shows_scroll_all_windows() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Hand; + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 60.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + assert!(!h.state().ui.tool_options.hand_scroll_all, "off by default"); + h.get_by_label("Scroll All Windows").click(); + h.run_steps(2); + assert!(h.state().ui.tool_options.hand_scroll_all, "the checkbox turns it on"); + h.get_by_label("Scroll All Windows").click(); + h.run_steps(2); + assert!(!h.state().ui.tool_options.hand_scroll_all, "and off again"); + } + + /// The Hand tool's options bar with Scroll All Windows on, two tiled documents and a document + /// window, as `the_hand_tool_options_bar_shows_scroll_all_windows` draws it. + fn options_bar_with_scroll_all() -> egui_kittest::Harness<'static, PhotocraftApp> { + use egui_kittest::Harness; + let mut app = app_with_tiles(); + app.ui.tool = Tool::Hand; + app.ui.tool_options.hand_scroll_all = true; + app.ui.views[0].zoom = 0.25; + app.ui.windows.push(DocWindow { + id: 7, + document: 1, + view: view(0.5, [400.0, 300.0], 0.0), + open: true, + floating: false, + focused: false, + position: None, + }); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 60.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::default()); + h.run_steps(4); + h + } + + #[test] + fn with_scroll_all_windows_on_the_zoom_buttons_change_only_the_active_view() { + use egui_kittest::kittest::Queryable; + for button in ["100%", "Fit Screen", "Fill Screen"] { + let mut h = options_bar_with_scroll_all(); + let others = (h.state().ui.views[1].clone(), h.state().ui.windows[0].view.clone()); + h.get_by_label(button).click(); + h.run_steps(2); + let active = &h.state().ui.views[0]; + assert!(active.zoom == 1.0 || active.fit_pending || active.fill_pending, "{button} changes the active view"); + let (tile, window) = (&h.state().ui.views[1], &h.state().ui.windows[0].view); + assert_eq!( + (tile.zoom, tile.center, tile.fit_pending, tile.fill_pending), + (others.0.zoom, others.0.center, false, false), + "{button}: the other tile stays" + ); + assert_eq!( + (window.zoom, window.center, window.fit_pending, window.fill_pending), + (others.1.zoom, others.1.center, false, false), + "{button}: the window stays" + ); + } + } + + #[test] + fn the_scroll_all_windows_checkbox_has_the_reference_tooltip() { + use egui_kittest::kittest::Queryable; + let mut h = options_bar_with_scroll_all(); + h.ctx.global_style_mut(|s| s.interaction.tooltip_delay = 0.0); + h.get_by_label("Scroll All Windows").hover(); + h.run_steps(4); + assert!(h.query_by_label("Scroll all open document windows when using the hand tool").is_some()); + } +} diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs index 631a7dac5b..722f4f2bb3 100644 --- a/crates/ui-egui/src/canvas/tabs.rs +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -811,7 +811,9 @@ pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) { if let Some([x, y]) = w.position { builder = builder.with_position([x, y]); } - let mut view = w.view.clone(); + // Read the window's view from `app.ui.windows`, not from `wins`: a Scroll All Windows drag in a + // window drawn earlier in this loop may have moved it since `wins` was taken. + let mut view = app.ui.windows.iter().find(|x| x.id == w.id).map_or_else(|| w.view.clone(), |x| x.view.clone()); let mut close = false; let mut focused = false; ctx.show_viewport_immediate(vid, builder, |ui, class| { @@ -824,7 +826,9 @@ pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) { } egui::CentralPanel::default().frame(egui::Frame::NONE.fill(crate::theme::Tokens::get(ui.ctx()).canvas)).show(ui, |ui| { let rect = ui.available_rect_before_wrap(); + app.drawing_window = Some(w.id); view = canvas_view(app, ui, w.document, rect, view.clone(), focused); + app.drawing_window = None; // Preferences › Zoom Resizes Windows: a zoom wraps the window around the image. crate::zoom_window_fit::follow(app, ui.ctx(), class, vid, &w, &mut view, rect); }); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 87e3bf32f7..5ce68488e1 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -276,6 +276,7 @@ fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() { command: "filter.blur.gaussianBlur".into(), params: json!({"radius": 999.0}), k: 1, + tool_colors: (app.session.tools.foreground, app.session.tools.background), }; let (told, cancelled) = std::sync::mpsc::channel(); app.filter_preview_worker @@ -329,6 +330,7 @@ fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::syn command: command.into(), params, k: 1, + tool_colors: (app.session.tools.foreground, app.session.tools.background), }; let doc = app.session.documents()[0].doc.clone(); let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); @@ -347,6 +349,7 @@ fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::syn key.target, &documents, &Default::default(), + Some(key.tool_colors), ) .map(|d| { let buffer = photocraft_compose::flatten(&d); @@ -396,6 +399,169 @@ fn a_held_preview_frame_stays_on_the_canvas_when_the_proxy_factor_changes() { assert_eq!((k, size), (1, [2400, 2200])); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn indexed_matte_preview_matches_commit_and_refreshes_tool_colors_inline_and_on_worker() { + for background in [false, true] { + for depth in [8, 16, 32] { + for matte in ["foreground", "background"] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.background_jobs = background; + app.run("file.new", json!({"width": 64, "height": 48, "depth": depth, "background": "transparent"})).unwrap(); + app.run("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + app.run("edit.colorSettings", json!({"workingRgb": "display-p3"})).unwrap(); + app.session + .edit("Translucent edge", |doc, active| { + let format = doc.pixel_format(); + doc.layer_mut(active.unwrap()) + .unwrap() + .surface_mut() + .unwrap() + .fill_rect(photocraft_geom::Rect::new(0, 0, 32, 48), &photocraft_raster::from_rgba(&format, [1.0, 0.0, 0.0, 0.5])); + Ok(()) + }) + .unwrap(); + let source = app.session.active().unwrap().doc.clone(); + let params = json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte}); + crate::filter_dialog::open(&mut app, "image.mode.indexedColor").unwrap(); + app.ui.dialogs.last_mut().unwrap().fields.extend(params.as_object().unwrap().clone()); + let ctx = egui::Context::default(); + let mut previous = None; + for (foreground, background_color) in [("#3366cc", "#cc6633"), ("#26bf59", "#bf26a6")] { + app.session.execute("tools.setColors", json!({"foreground": foreground, "background": background_color})).unwrap(); + let colors = (app.session.tools.foreground, app.session.tools.background); + let shown = ensure_filter_preview(&mut app, 0, &ctx); + if background { + assert!(shown.is_none(), "old tool colors must not remain visible"); + } + drive_until(&mut app, &ctx, "the current matte colors", |app| { + app.filter_preview.as_ref().is_some_and(|p| p.key.tool_colors == colors && p.result.is_some()) + }); + let preview = app.filter_preview.as_ref().unwrap().result.as_ref().unwrap(); + let mut applied = photocraft_engine::Session::new(); + applied.color.settings = app.session.color.settings.clone(); + applied.tools.foreground = colors.0; + applied.tools.background = colors.1; + applied.add_document((*source).clone(), None); + applied.execute("image.mode.indexedColor", params.clone()).unwrap(); + let committed = &applied.active().unwrap().doc; + assert_eq!(preview.icc_profile, source.icc_profile); + assert_eq!(preview.color_table, committed.color_table); + let actual = preview.layers[0].surface().unwrap().read_region(preview.bounds()); + let expected = committed.layers[0].surface().unwrap().read_region(committed.bounds()); + assert_eq!(actual, expected, "{matte}, {depth}-bit, worker={background}"); + if let Some(previous) = previous { + assert_ne!(actual, previous, "changing the selected tool color refreshes the pixels"); + } + previous = Some(actual); + assert_eq!(app.session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Rgb, "preview does not commit"); + } + } + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn cross_scale_indexed_matte_preview_rejects_old_tool_colors_from_cached_and_worker_results() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.background_jobs = true; + app.run("file.new", json!({"width": 2400, "height": 2200, "depth": 8, "background": "transparent"})).unwrap(); + app.run("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + app.run("edit.colorSettings", json!({"workingRgb": "display-p3"})).unwrap(); + app.session + .edit("Translucent edge", |doc, active| { + let format = doc.pixel_format(); + doc.layer_mut(active.unwrap()) + .unwrap() + .surface_mut() + .unwrap() + .fill_rect(photocraft_geom::Rect::new(0, 0, 32, 48), &photocraft_raster::from_rgba(&format, [1.0, 0.0, 0.0, 0.5])); + Ok(()) + }) + .unwrap(); + app.ui.views.get_mut(0).expect("the new document's view").zoom = 0.25; + let params = json!({"palette": "exact", "forced": "none", "dither": "none", "matte": "foreground"}); + crate::filter_dialog::open(&mut app, "image.mode.indexedColor").unwrap(); + app.ui.dialogs.last_mut().unwrap().fields.extend(params.as_object().unwrap().clone()); + app.session.execute("tools.setColors", json!({"foreground": "#3366cc", "background": "#cc6633"})).unwrap(); + let ctx = egui::Context::default(); + drive_until(&mut app, &ctx, "the first indexed preview", |a| a.filter_preview.as_ref().is_some_and(|p| p.result.is_some())); + let old = app.filter_preview.as_ref().expect("the first preview").key.clone(); + assert_eq!(old.k, 2, "the zoomed-out large document uses the reduced preview"); + + app.session.execute("tools.setColors", json!({"foreground": "#26bf59", "background": "#bf26a6"})).unwrap(); + app.ui.views.get_mut(0).expect("the new document's view").zoom = 1.0; + let new_colors = (app.session.tools.foreground, app.session.tools.background); + let new = crate::filter_dialog::FilterPreviewKey { k: 1, tool_colors: new_colors, ..old.clone() }; + assert_ne!(old.tool_colors, new.tool_colors); + assert_ne!(old.k, new.k, "the cache and request use different preview factors"); + + // Keep the current worker pending so the only possible frame is the cached old-color one. + let (release_new, wait_new) = std::sync::mpsc::channel(); + app.filter_preview_worker + .start(new.clone(), ctx.clone(), move |_| { + wait_new.recv_timeout(std::time::Duration::from_secs(60)).expect("the test releases the job"); + crate::dialogs::filter_preview_worker::Computed { result: None, ms: 0.0 } + }) + .expect("the worker starts"); + assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none(), "the cached old-color frame is not painted while the new worker runs"); + release_new.send(()).expect("released"); + drive_until(&mut app, &ctx, "the new worker to finish", |a| !a.filter_preview_worker.busy()); + assert_eq!(app.filter_preview.as_ref().expect("the current request").key, new); + assert!(app.filter_preview.as_ref().unwrap().result.is_none()); + + // Start an old-color worker while its request is current, then move the dialog to a new + // cross-scale request before the old result lands. Its real preview must not replace the + // current request through the loose worker-result gate. + app.session.execute("tools.setColors", json!({"foreground": "#3366cc", "background": "#cc6633"})).unwrap(); + app.ui.views.get_mut(0).expect("the new document's view").zoom = 0.25; + let old_worker = old.clone(); + let doc = app.session.documents()[0].doc.clone(); + let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); + let color = app.session.color.settings.clone(); + let (release_old, wait_old) = std::sync::mpsc::channel(); + app.filter_preview_worker + .start(old_worker.clone(), ctx.clone(), move |_| { + wait_old.recv_timeout(std::time::Duration::from_secs(60)).expect("the test releases the job"); + let result = crate::filter_dialog::preview_document_for_target( + &doc, + old_worker.active, + &old_worker.command, + &old_worker.params, + old_worker.k, + None, + old_worker.target, + &documents, + &color, + Some(old_worker.tool_colors), + ) + .map(|doc| { + let buffer = photocraft_compose::flatten(&doc); + (std::sync::Arc::new(doc), buffer) + }); + crate::dialogs::filter_preview_worker::Computed { result, ms: 0.0 } + }) + .expect("the worker starts"); + assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none(), "the old cached request is not current"); + + app.session.execute("tools.setColors", json!({"foreground": "#26bf59", "background": "#bf26a6"})).unwrap(); + app.ui.views.get_mut(0).expect("the new document's view").zoom = 1.0; + app.ui.dialogs[0].fields.insert("matte".into(), json!("background")); + let mut new_late = new.clone(); + new_late.params.as_object_mut().unwrap().insert("matte".into(), json!("background")); + assert!(ensure_filter_preview(&mut app, 0, &ctx).is_none(), "the current request has no result while the old worker runs"); + release_old.send(()).expect("released"); + drive_until(&mut app, &ctx, "the stale old-color worker to finish", |a| { + if let Some(shown) = &a.filter_preview { + assert_eq!(shown.key.tool_colors, new.tool_colors, "the stale old-color worker result was not painted"); + assert_ne!(shown.key.k, old.k, "the stale old-scale worker result was not painted"); + } + a.filter_preview.as_ref().is_some_and(|p| p.key == new_late && p.result.is_some()) && !a.filter_preview_worker.busy() + }); + assert_eq!(app.filter_preview.as_ref().expect("the current request").key, new_late); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_preview_computed_mid_drag_reaches_the_canvas_and_then_converges() { @@ -502,6 +668,7 @@ fn a_mid_drag_empty_result_leaves_the_preview_alone() { command: "filter.blur.gaussianBlur".into(), params: json!({"radius": moved}), k: 1, + tool_colors: (app.session.tools.foreground, app.session.tools.background), }; let (release_empty, wait) = std::sync::mpsc::channel::<()>(); app.filter_preview_worker @@ -2137,7 +2304,7 @@ fn brush_drag_shows_the_real_stroke_and_commits_it() { assert_eq!(alpha(&app.session.documents()[0].doc, 40, 30), 0.0, "not committed yet"); // The canvas redraws only what the stroke touched. let dk = canvas_display(&app, &app.session.documents()[0].doc, None).1; - let d = damage_since(&app, 0, (rev, dk), (rev, key), dk, None).unwrap(); + let d = damage_since(&app, 0, (rev, dk), (rev, key), dk, (rev, None)).unwrap(); assert!(d.contains(40, 30) && !d.contains(40, 2) && d.height() < 60, "{d:?}"); tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 30.0 }, m); let doc = app.session.documents()[0].doc.clone(); @@ -2145,6 +2312,60 @@ fn brush_drag_shows_the_real_stroke_and_commits_it() { assert_eq!((alpha(&doc, 40, 30), alpha(&doc, 40, 38)), (alpha(&shown, 40, 30), alpha(&shown, 40, 38)), "commit matches the preview"); } +/// #9329 PR C: Paste Into is three revisions; the canvas redraws what the whole command +/// changed (the pasted area), not the whole document as when only one revision counted. +#[test] +fn paste_into_refreshes_only_the_pasted_area() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.background_jobs = false; + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.run("select.rect", json!({"x": 40, "y": 40, "width": 100, "height": 100})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("select.rect", json!({"x": 500, "y": 400, "width": 90, "height": 60})).unwrap(); + ensure_texture(&mut app, &ctx, 0, None).expect("a texture"); + let rev = app.session.active().unwrap().revision; + app.perf.last_refresh_px = 0; + app.run("edit.pasteSpecial.pasteInto", json!({})).unwrap(); + assert!(app.session.active().unwrap().revision >= rev + 2, "several revisions"); + ensure_texture(&mut app, &ctx, 0, None).expect("a texture"); + let px = app.perf.last_refresh_px; + assert!(px > 0 && px < 800 * 600 / 4, "refreshed {px} px of {}", 800 * 600); +} + +/// The Move tool's Auto-Select pick is its own revision that changes no pixels: the drag +/// that follows still redraws only where the layer was and is. +#[test] +fn auto_select_move_is_still_bounded() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.background_jobs = false; + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + for (x, color) in [(100, "#ff0000"), (500, "#0000ff")] { + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": x, "y": 100, "width": 40, "height": 40})).unwrap(); + app.run("edit.fill", json!({"color": color})).unwrap(); + } + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = true; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + let active = app.session.active().unwrap().active_layer; + ensure_texture(&mut app, &ctx, 0, None).expect("a texture"); + let rev = app.session.active().unwrap().revision; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 120.0, y: 120.0, pressure: 1.0 }, m); + assert_ne!(app.session.active().unwrap().active_layer, active, "Auto-Select picked the red layer"); + assert_eq!(app.session.active().unwrap().revision, rev + 1, "the pick is one revision"); + tool_event(&mut app, ToolEvent::Move { x: 150.0, y: 130.0, pressure: 1.0 }, m); + app.perf.last_refresh_px = 0; + ensure_texture(&mut app, &ctx, 0, None).expect("a texture"); + let px = app.perf.last_refresh_px; + assert!(px > 0 && px < 800 * 600 / 4, "refreshed {px} px of {}", 800 * 600); + tool_event(&mut app, ToolEvent::Up { x: 150.0, y: 130.0 }, m); +} + #[test] fn live_stroke_uses_pen_tilt_and_updates_a_reduced_texture_partially() { // Pen tilt drives the size; the preview must use the tilt the commit gets. The document @@ -3119,3 +3340,33 @@ fn fade_dialog_previews_the_faded_layer_and_cancel_keeps_the_document() { assert_eq!(st.history.past_len(), steps + 1); } } + +#[test] +fn free_transform_redraws_only_the_moving_layer_when_the_box_opens_and_closes() { + // Opening the box swapped the canvas to a preview document with no damage for it, so a + // gigapixel canvas recomposited in full (over a second) on every ⌘T, and again on Cancel. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200, "background": "transparent"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(20, 20, 60, 50), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let rev = app.session.documents()[0].revision; + crate::transform_tool::begin(&mut app, &egui::Context::default()).expect("the box opens"); + let (_, key) = display_doc(&mut app, 0); + assert_eq!(key, crate::transform_tool::preview_key(app.transform_preview.as_ref().unwrap().session)); + let dk = canvas_display(&app, &app.session.documents()[0].doc, None).1; + let opened = damage_since(&app, 0, (rev, dk), (rev, key), dk, (rev, None)).expect("opening the box has a damage area"); + assert!(opened.contains(20, 20) && opened.contains(59, 49), "{opened:?}"); + assert!(opened.width() < 400 && opened.height() < 200, "not the whole canvas: {opened:?}"); + let canceled = damage_since(&app, 0, (rev, key ^ dk), (rev, 0), dk, (rev, None)).expect("canceling has one too"); + assert_eq!(canceled, opened); + // A commit (one revision later) adds what it changed; anything else redraws everything. + let moved = photocraft_geom::Rect::new(100, 20, 140, 50); + let committed = damage_since(&app, 0, (rev, key ^ dk), (rev + 1, 0), dk, (rev, Some(moved))).expect("committing too"); + assert!(committed.contains(20, 20) && committed.contains(139, 49), "{committed:?}"); + assert!(damage_since(&app, 0, (rev, key ^ dk), (rev + 2, 0), dk, (rev + 1, Some(moved))).is_none(), "a later revision isn't ours"); +} diff --git a/crates/ui-egui/src/canvas/textures.rs b/crates/ui-egui/src/canvas/textures.rs index 702cf6c3bd..d8bb2a1290 100644 --- a/crates/ui-egui/src/canvas/textures.rs +++ b/crates/ui-egui/src/canvas/textures.rs @@ -122,7 +122,7 @@ pub(crate) fn ensure_texture_in_view( let output = display; let (revision, last_damage, id) = { let st = app.session.documents().get(idx)?; - (st.revision, st.last_damage.map(|r| if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }), st.doc.id) + (st.revision, (st.damage_from(), st.last_damage.map(|r| if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) })), st.doc.id) }; let (mut doc, mut preview_key) = display_doc(app, idx); // A filter dialog's live preview: the GPU canvas draws it from its own texture, but this CPU @@ -317,9 +317,17 @@ fn render_detail( } /// What changed since a canvas cache showed (`revision`, `preview key`) `seen`, when only a -/// rectangle did: the last edit's damage, or the live stroke's dabs since then. Cached keys have -/// the colour display's key folded in (`^ display_key`); `now`'s is still raw. -pub(crate) fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), now: (u64, u64), display_key: u64, last_damage: Option) -> Option { +/// rectangle did: the document's damage since revision `damage_from` (one revision, or a whole +/// command's span: [`photocraft_engine::DocState::damage_from`]), or the live stroke's dabs since +/// then. Cached keys have the colour display's key folded in (`^ display_key`); `now`'s is still raw. +pub(crate) fn damage_since( + app: &PhotocraftApp, + idx: usize, + seen: (u64, u64), + now: (u64, u64), + display_key: u64, + (damage_from, last_damage): (u64, Option), +) -> Option { // A brush stroke committed with the pixels its live preview already showed: only the steps // this cache hadn't shown yet (usually nothing), not the stroke's whole bounding box. if seen.0 + 1 == now.0 @@ -336,9 +344,18 @@ pub(crate) fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), no }; return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); } - if seen.1 == now.1 ^ display_key && seen.0 + 1 == now.0 { + // `seen` is within the span the document's damage covers. + let in_span = seen.0 >= damage_from && seen.0 < now.0; + if seen.1 == now.1 ^ display_key && in_span { return last_damage; } + // Opening, canceling or committing a Free Transform box: the moving layer and the layers + // drawn over the box, not the whole document (a gigapixel canvas took over a second). + if let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::transform_tool::damage(app, st.doc.id, (seen.0, seen.1 ^ display_key), now, last_damage) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } if seen.0 == now.0 && let Some(st) = app.session.documents().get(idx) && let Some(r) = crate::type_transform::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) @@ -360,9 +377,9 @@ pub(crate) fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), no { return Some(r); } - // Between a Move drag's offsets: where the moving layers were and are (Auto-Select's pick - // at the press changes no pixels). - if (seen.0 == now.0 || (seen.0 + 1 == now.0 && last_damage.is_some_and(|r| r.is_empty()))) + // Between a Move drag's offsets: where the moving layers were and are. Revisions that changed + // no pixels since `seen` (Auto-Select's pick at the press) count as the same document. + if (seen.0 == now.0 || (in_span && last_damage.is_some_and(|r| r.is_empty()))) && let Some(st) = app.session.documents().get(idx) && let Some(r) = crate::move_ui::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) { @@ -457,11 +474,10 @@ pub(crate) fn effect_reach(layers: &[photocraft_doc::Layer]) -> i32 { /// Returns false if there is no GPU canvas. pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible: DRect) -> bool { let Some(gpu) = app.gpu.clone() else { return false }; - let Some((revision, last_damage, id)) = app - .session - .documents() - .get(idx) - .map(|st| (st.revision, st.last_damage.map(|r| if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }), st.doc.id)) + let Some((revision, last_damage, id)) = + app.session.documents().get(idx).map(|st| { + (st.revision, (st.damage_from(), st.last_damage.map(|r| if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) })), st.doc.id) + }) else { return false; }; diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index 84b69b26cf..c34f4d6622 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -111,6 +111,16 @@ pub(crate) fn close_path(painter: &Painter, at: Pos2) -> CursorIcon { outline(painter, at, vec![close_ring()], true) } +/// The Pen's pointer over an endpoint a click would carry the path on from (#9356): the centre +/// cross with a short slash below right, as Photoshop's pen shows one there. +pub(crate) fn continue_path(painter: &Painter, at: Pos2) -> CursorIcon { + outline(painter, at, vec![continue_slash()], true) +} + +fn continue_slash() -> Vec { + [(6.5, 12.5), (11.5, 5.5), (12.5, 6.5), (7.5, 13.5)].into_iter().map(|(x, y)| vec2(x, y)).collect() +} + fn close_ring() -> Vec { (0..16).map(|i| (i as f32 / 16.0 * std::f32::consts::TAU, vec2(9.0, 9.0))).map(|(a, c)| c + vec2(a.cos(), a.sin()) * 3.5).collect() } diff --git a/crates/ui-egui/src/canvas/tool_cursor/tests.rs b/crates/ui-egui/src/canvas/tool_cursor/tests.rs index bd5b40c97e..ec003d4845 100644 --- a/crates/ui-egui/src/canvas/tool_cursor/tests.rs +++ b/crates/ui-egui/src/canvas/tool_cursor/tests.rs @@ -1140,3 +1140,16 @@ mod benchmark_stats { assert_eq!(percentile(&[4.5], 0.95), 4.5, "one sample"); } } + +/// #9356: the continue-path pointer is the centre cross with a slash below right. +#[test] +fn continue_path_bitmap_has_the_centre_cross_and_a_slash_beside_it() { + for scale in [1.0, 2.0] { + let image = rasterize(&Shape::Outline { rings: vec![continue_slash()].into(), centre: true }, scale).unwrap(); + let [x, y] = image.hotspot; + let at = |dx: f32, dy: f32| alpha(&image, x + (dx * scale) as u16, y + (dy * scale) as u16); + assert!(at(0.0, 0.0) > 230, "the centre cross"); + assert!(at(9.5, 9.5) > 0, "the slash"); + assert_eq!(at(0.0, 9.0), 0, "apart from the cross"); + } +} diff --git a/crates/ui-egui/src/canvas/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs index 6c9c890571..88aec042e5 100644 --- a/crates/ui-egui/src/canvas/tool_feedback.rs +++ b/crates/ui-egui/src/canvas/tool_feedback.rs @@ -19,6 +19,8 @@ pub enum Badge { Intersect, /// Four arrows: a press drags the point under the pointer (the Curvature Pen over an anchor). Move, + /// One right-pointing arrow: a press drags the patch (the Patch tool over the selection). + Arrow, } impl Badge { @@ -122,9 +124,12 @@ pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option Vec<[Pos2; 2]> { } v } + Badge::Arrow => { + let a = h * 0.6; + vec![[c - vec2(h, 0.0), c + vec2(h, 0.0)], [c + vec2(h, 0.0), c + vec2(h - a, a)], [c + vec2(h, 0.0), c + vec2(h - a, -a)]] + } Badge::Intersect => { let d = h * 0.8; vec![[c + vec2(-d, -d), c + vec2(d, d)], [c + vec2(-d, d), c + vec2(d, -d)]] @@ -319,3 +328,7 @@ mod tests { assert!(e.len() >= 16 && e.iter().all(|p| p.x >= -0.01 && p.x <= 100.01 && p.y >= -0.01 && p.y <= 50.01)); } } + +#[cfg(test)] +#[path = "../patch_cursor_badge_tests.rs"] +mod patch_cursor_badge_tests; diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index f148b8dfa5..80146394ec 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -145,7 +145,7 @@ fn filter_event_before_tool(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui:: if crate::distort_ui::pointer(app, ev, mods) { return None; } - if crate::perspective_crop_ui::pointer(app, ev) { + if crate::perspective_crop_ui::pointer(app, ev, mods) { return None; } // Window › Modifier Keys: sticky Shift/⌘/⌥ act as held keys. @@ -359,6 +359,42 @@ fn handle_eyedropper_event(app: &mut PhotocraftApp, tool: Tool, ev: ToolEvent, m true } +/// A Mixer Brush press the engine refused: Indexed Color and Bitmap documents answer it with the +/// reference's alert (#11958); anything else goes to the status bar, as before. +fn mixer_press_failed(app: &mut PhotocraftApp, message: String) { + use photocraft_engine::brush_cmds::mixer_live::{BITMAP_REFUSAL, INDEXED_REFUSAL}; + if message == INDEXED_REFUSAL || message == BITMAP_REFUSAL { + // One alert, even if more presses arrive while it is open (`ui.pointer` can send them). + let shown = + app.ui.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message)); + if !shown { + let params = json!({ "message": message }).as_object().cloned().unwrap_or_default(); + app.ui.open_dialog(crate::state::DialogKind::Error, params); + } + } else { + app.ui.status = message; + app.ui.status_error = true; + } +} + +/// The Brush's chosen Clear paints as Normal on the Background, and its Mode then reads Normal +/// (#11897): at the press of a Brush stroke on the Background's own pixels, Clear (chosen in the +/// options bar, not a held `~`) is turned off, so the stroke is sent as Normal. A Background whose +/// pixels are locked refuses the stroke, so Clear stays chosen there. +fn clear_off_on_background(app: &mut PhotocraftApp, tool: Tool) { + let on_background = app.session.active().is_some_and(|st| { + st.active_layer.is_some_and(|id| { + st.doc.is_background(id) && { + let locks = st.doc.effective_locks(id); + !locks.pixels && !locks.all + } + }) + }); + if tool == Tool::Brush && app.ui.tool_options.brush_clear && !app.held_erase && on_background && paint_target(app) == serde_json::json!("pixels") { + app.ui.tool_options.brush_clear = false; + } +} + /// Tool state machine. Shared by mouse input and automation. pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { if consumes_cancelled_vector_event(app, ev) { @@ -399,9 +435,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) // (⌥-click with the Clone Stamp or Healing Brush only sets the source). let sets_source = matches!(tool, Tool::CloneStamp | Tool::Healing) && mods.alt; // Painting on or moving a hidden layer is refused at the press, as in Photoshop (#571). - if !sets_source && let Some(why) = hidden_target(app, tool) { - app.ui.status = why.into(); - app.ui.status_error = true; + if !sets_source && press_refused(app, tool) { return; } if !sets_source && crate::rasterize_prompt::intercept(app, tool, x, y, pressure) { @@ -524,6 +558,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) _ => {} } crate::paint_mouse::sync_tool_brush(app); + clear_off_on_background(app, tool); // Clear mode (`~` held, or chosen in the options bar) erases with the tool's own brush. let clear = crate::paint_mouse::clears(app, tool); let erase = std::mem::take(&mut app.secondary_erase) || tool == Tool::Eraser || clear; @@ -563,8 +598,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) && !LiveMixer::defers_to_release(&app.session, &p).is_ok_and(|deferred| deferred) { if let Err(e) = LiveMixer::begin(&app.session, &p) { - app.ui.status = e.to_string(); - app.ui.status_error = true; + mixer_press_failed(app, e.to_string()); } app.drag = None; } @@ -680,6 +714,23 @@ fn hidden_target(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { photocraft_engine::hidden_target::refusal(&app.session, cmd, &json!({})) } +/// The press-time refusals: a hidden target layer (#571), and for the Brush a locked layer or a +/// group's pixels. The Brush says why in an alert, as in Photoshop (#11898); the other tools say +/// a hidden target in the status bar. True when the press is refused. +fn press_refused(app: &mut PhotocraftApp, tool: Tool) -> bool { + let hidden = hidden_target(app, tool); + if let Some(message) = crate::brush_refusal::alert(app, tool, hidden.is_some()) { + crate::brush_refusal::prompt(app, &message); + return true; + } + if let Some(why) = hidden { + app.ui.status = why.into(); + app.ui.status_error = true; + return true; + } + false +} + /// Is document point `p` inside the active document's selection? fn inside_selection(app: &PhotocraftApp, p: [f64; 2]) -> bool { app.session.active().and_then(|st| st.doc.selection.as_ref()).is_some_and(|sel| covers(sel, p)) diff --git a/crates/ui-egui/src/canvas/viewport_pages.rs b/crates/ui-egui/src/canvas/viewport_pages.rs index 07933ede30..ce0c119d09 100644 --- a/crates/ui-egui/src/canvas/viewport_pages.rs +++ b/crates/ui-egui/src/canvas/viewport_pages.rs @@ -609,12 +609,14 @@ pub(super) fn show(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, xf: if app.ui.view.pattern_preview || gpu.fault().is_some() { return false; } - let Some((revision, last_damage, id, size)) = app - .session - .documents() - .get(idx) - .map(|st| (st.revision, st.last_damage.map(|r| if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }), st.doc.id, st.doc.size)) - else { + let Some((revision, last_damage, id, size)) = app.session.documents().get(idx).map(|st| { + ( + st.revision, + (st.damage_from(), st.last_damage.map(|r| if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) })), + st.doc.id, + st.doc.size, + ) + }) else { return false; }; let size = [size.width, size.height]; diff --git a/crates/ui-egui/src/color_replacement_alt_click_tests.rs b/crates/ui-egui/src/color_replacement_alt_click_tests.rs new file mode 100644 index 0000000000..8fd1533a02 --- /dev/null +++ b/crates/ui-egui/src/color_replacement_alt_click_tests.rs @@ -0,0 +1,77 @@ +//! #11914: holding Alt turns the Color Replacement tool into the Eyedropper. Alt+click and +//! Alt+drag set the foreground colour, add no history state and change no pixel; Ctrl+Alt keeps +//! its brush-resize meaning and a plain click still paints. + +use egui::Modifiers; +use serde_json::json; + +use super::*; +use crate::canvas::{ToolEvent, tool_event}; + +/// A 400 × 300 RGB document: a green layer (30,180,60), blue foreground, the Color Replacement tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#1eb43c"})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#0000ff"})).unwrap(); + app.ui.tool = Tool::ColorReplacement; + app.sync_views(); + app +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn foreground(app: &PhotocraftApp) -> [u8; 3] { + let c = app.session.tools.foreground; + [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8) +} + +fn pixel(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] { + let st = app.session.active().unwrap(); + let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8) +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +#[test] +fn alt_click_and_drag_pick_the_foreground() { + let mut app = app(); + let before = steps(&app); + drag(&mut app, [300.0, 60.0], [300.0, 60.0], Modifiers::ALT); + assert_eq!(foreground(&app), [30, 180, 60], "the green under the click"); + assert_eq!(steps(&app), before, "no history state"); + assert_eq!(pixel(&app, 300, 60), [30, 180, 60], "no pixel changed"); + // A drag samples as it goes, as the Eyedropper does. + app.run("tools.setColors", json!({"foreground": "#0000ff"})).unwrap(); + drag(&mut app, [100.0, 100.0], [200.0, 150.0], Modifiers::ALT); + assert_eq!(foreground(&app), [30, 180, 60]); + assert_eq!(steps(&app), before); +} + +#[test] +fn alt_shows_the_eyedropper_and_ctrl_alt_resizes() { + let alt = Modifiers::ALT; + let ctrl_alt = Modifiers { alt: true, ctrl: true, ..Modifiers::NONE }; + assert!(alt_samples(Tool::ColorReplacement, alt)); + assert!(alt_picks(Tool::ColorReplacement, alt), "the cursor shows the eyedropper while Alt is held"); + assert!(!alt_samples(Tool::ColorReplacement, ctrl_alt), "Ctrl+Alt is the brush-resize drag"); + assert!(!alt_samples(Tool::ColorReplacement, Modifiers::NONE)); +} + +#[test] +fn a_plain_click_still_paints() { + let mut app = app(); + let before = steps(&app); + drag(&mut app, [300.0, 60.0], [310.0, 60.0], Modifiers::NONE); + assert_eq!(steps(&app), before + 1, "a Color Replacement state"); + assert_ne!(pixel(&app, 300, 60), [30, 180, 60], "the green was replaced"); + assert_eq!(foreground(&app), [0, 0, 255]); +} diff --git a/crates/ui-egui/src/color_replacement_tests.rs b/crates/ui-egui/src/color_replacement_tests.rs index 64f04f3c73..87adc1f64c 100644 --- a/crates/ui-egui/src/color_replacement_tests.rs +++ b/crates/ui-egui/src/color_replacement_tests.rs @@ -115,7 +115,8 @@ fn contiguous_limits_skip_a_matching_island_that_discontiguous_recolours() { /// 8 (the live stroke keeps its working pixels in the layer's depth between dabs). #[test] fn a_stroke_is_drawn_live_and_is_one_history_step() { - for depth in [8, 32] { + // Color Replacement refuses 32-bit RGB documents, as the reference application does (#11923). + for depth in [8, 16] { live_stroke_at(depth); } } @@ -147,7 +148,7 @@ fn live_stroke_at(depth: u32) { } let st = app.session.active().unwrap(); assert_eq!(st.history.past_len(), steps + 1, "one History step"); - assert_eq!(st.history.entries().last().map(|e| e.to_string()).as_deref(), Some("Color Replacement")); + assert_eq!(st.history.entries().last().map(|e| e.to_string()).as_deref(), Some("Color Replacement Tool")); app.run("edit.undo", json!({})).unwrap(); assert_eq!(rgba(&app, 20, 20), before, "one undo restores the pixels"); app.run("edit.redo", json!({})).unwrap(); diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 3c61c88f9f..7e7a7186b0 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -614,6 +614,10 @@ fn crop_fill_param(p: &Value) -> std::result::Result, String> { /// keeps a pin and `{"pinned": true}` keeps a dragged position (#10890). fn panels_patch(app: &PhotocraftApp, patch: Option<&Value>) -> std::result::Result, String> { let Some(mut patch) = patch.cloned() else { return Ok(None) }; + // Saved panels read an unknown side as the default; a control request is still refused. + if let Some(side) = patch.get("toolbar_side") { + serde_json::from_value::(side.clone()).map_err(|e| format!("panels.toolbar_side: {e}"))?; + } if let Some(obj) = patch.as_object_mut() && let Some(bar) = obj.get("task_bar") { @@ -725,11 +729,12 @@ impl PanelSet { } } + /// Applies the Color panel state and queues the requested end-dock width for the next frame. fn apply_color_and_width(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) { if let Some(v) = self.color_panel.take() { app.ui.color_panel = v; } - // Right dock width in points (clamped to the dock's 250..=520 range), applied next frame. + // End dock width in points, clamped to its window-dependent range and applied next frame. if let Some(w) = self.dock_width { crate::panels::request_dock_width(ctx, w as f32); } @@ -1342,11 +1347,11 @@ fn parse_pointer_event(i: usize, e: &Value) -> std::result::Result bool { - let took = pointer_eyedropper_took(app, ctx, g, s) || color_range_took(app, g, s) || (g.secondary && secondary_menu_took(app, ctx, g, s)); + let took = pointer_eyedropper_took(app, ctx, g, s) || color_range_took(app, g, s); if took && matches!(s.ev, ToolEvent::Up { .. }) && !g.secondary && !g.middle { release_taken_drag(app, g); } - took + took || preview_locator_took(app, g, s) || (g.secondary && secondary_menu_took(app, ctx, g, s)) } /// A sampler (Color Picker, Curves/Levels or Properties eyedroppers, Curves ⌘-click, Color @@ -1360,6 +1365,28 @@ fn release_taken_drag(app: &mut PhotocraftApp, g: &PointerGesture) { } } +/// A filter dialog with a preview window on top: the image is its locator, as for the mouse +/// (#9648). A press with the primary button centres the window there; every other event +/// is consumed too, so nothing reaches the tool under the dialog, except the moves and release of +/// a tool gesture begun before the dialog opened, which finish it along the path they draw. A Crop +/// frame or Straighten drag is one too, though the Crop tool keeps it apart from `app.drag`. While +/// one is open, a second primary press (no mouse can make one) is dropped: it neither centres the +/// window nor reaches the tool, so no locator press splits the gesture's moves and release. +fn preview_locator_took(app: &mut PhotocraftApp, g: &PointerGesture, s: &PointerSample) -> bool { + if crate::filter_preview_ui::locator(app).is_none() { + return false; + } + let down = matches!(s.ev, ToolEvent::Down { .. }); + let tool_gesture = app.drag.is_some() || app.crop.drag.is_some() || app.crop.straighten.line.is_some(); + if !g.secondary && !g.middle && tool_gesture { + return down; + } + if down && !g.secondary && !g.middle && !g.space { + crate::filter_preview_ui::center_at(app, s.x, s.y); + } + true +} + fn pointer_eyedropper_took(app: &mut PhotocraftApp, ctx: &egui::Context, g: &PointerGesture, s: &PointerSample) -> bool { let (x, y) = (s.x, s.y); let down = matches!(s.ev, ToolEvent::Down { .. }); diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 5761661b1a..70e35fb89b 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -138,7 +138,7 @@ fn perf_output_includes_slow_frames() { assert_eq!(call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["perf"]["slowFrames"], json!([])); app.slow_frames.set_threshold_ms(0.0); app.run("file.new", json!({"width": 64, "height": 32})).unwrap(); - app.finish_frame(1.0); + app.finish_frame(&ctx, 1.0); let frames = call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["perf"]["slowFrames"].clone(); let last = frames.as_array().and_then(|f| f.last()).expect("a slow frame").clone(); assert_eq!(last["command"], "file.new", "{last}"); @@ -156,7 +156,7 @@ fn perf_output_includes_slow_frames() { let played = app.run("actions.play", json!({"action": "Zoom"})).unwrap(); assert_eq!(played["ran"], 2, "{played}"); let outer_ms = app.perf.command_ms; - app.finish_frame(1.0); + app.finish_frame(&ctx, 1.0); let frames = call(&mut app, &ctx, "ui.inspect", json!({}))["result"]["perf"]["slowFrames"].clone(); let last = frames.as_array().and_then(|f| f.last()).expect("a slow frame").clone(); assert_eq!(last["command"], "actions.play", "{last}"); @@ -1193,7 +1193,7 @@ fn ui_set_opens_the_brush_preset_picker_and_sets_its_cards() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); let ctx = egui::Context::default(); let list = &app.ui.brush_picker_list; - assert!(list.show_name && list.show_stroke && list.show_tip, "every card part is on by default"); + assert!(list.show_name && list.show_stroke && !list.show_tip, "the cards show the name and the stroke by default"); let r = call(&mut app, &ctx, "ui.set", json!({"tool": "brush", "brushPicker": [120, 80], "brushPickerStroke": false})); assert_eq!(r["ok"], true, "{r}"); assert_eq!(app.ui.brush_picker, Some([120.0, 80.0])); @@ -1237,11 +1237,11 @@ fn ui_inspect_tracks_brush_picker_open_and_closed() { assert!(open["result"]["brushPicker"]["pos"].is_array(), "{open}"); assert_eq!(open["result"]["brushPicker"]["list"]["showName"], true); assert_eq!(open["result"]["brushPicker"]["list"]["showStroke"], true); - assert_eq!(open["result"]["brushPicker"]["list"]["showTip"], true); + assert_eq!(open["result"]["brushPicker"]["list"]["showTip"], false); - assert_eq!(call(&mut app, &ctx, "ui.set", json!({"brushPickerTip": false}))["ok"], true); + assert_eq!(call(&mut app, &ctx, "ui.set", json!({"brushPickerTip": true}))["ok"], true); let changed = call(&mut app, &ctx, "ui.inspect", json!({})); - assert_eq!(changed["result"]["brushPicker"]["list"]["showTip"], false); + assert_eq!(changed["result"]["brushPicker"]["list"]["showTip"], true); assert_eq!(call(&mut app, &ctx, "ui.set", json!({"brushPicker": null}))["ok"], true); let closed_again = call(&mut app, &ctx, "ui.inspect", json!({})); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 14d20537fd..112bd79394 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -277,13 +277,16 @@ pub(crate) fn close_box(ui: &mut egui::Ui, rect: egui::Rect) -> bool { /// it. Returns `Some(true)` / `Some(false)` when the body itself answered OK / Cancel. /// The body of a command dialog: the first handler whose marker the fields carry. The prompts and /// small editors come first; the rest are in `command_body_more`. -/// The delete confirmations: a layer from the Layers panel's trash, or a note (#11788). +/// The delete confirmations: a layer from the Layers panel's trash, a note (#11788), or all notes +/// (#11791). fn delete_prompt(fields: &Fields) -> bool { - crate::delete_layer_prompt::owns(fields) || crate::analysis_ui::owns_delete_note(fields) + crate::delete_layer_prompt::owns(fields) || crate::analysis_ui::owns_delete_note(fields) || crate::analysis_ui::owns_clear_notes(fields) } fn delete_prompt_body(ui: &mut egui::Ui, fields: &mut Fields) { - if crate::analysis_ui::owns_delete_note(fields) { + if crate::analysis_ui::owns_clear_notes(fields) { + crate::analysis_ui::clear_notes_body(ui); + } else if crate::analysis_ui::owns_delete_note(fields) { crate::analysis_ui::delete_note_body(ui, fields); } else { crate::delete_layer_prompt::body(ui, fields); @@ -404,6 +407,7 @@ fn dialog_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: & DialogKind::LayerStyle => outcome = crate::layer_style::body_with_response(app, ui, fields, interactive), DialogKind::Error => { ui.label(fields.get("message").and_then(Value::as_str).unwrap_or("Error")); + dont_show_again::body(ui, fields); } } outcome @@ -884,6 +888,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[ crate::shape_dialog::owns, crate::delete_layer_prompt::owns, crate::analysis_ui::owns_delete_note, + crate::analysis_ui::owns_clear_notes, crate::disk_change_prompt::owns, crate::actions::owns_stop_message, crate::actions::owns_insert_stop, @@ -1119,6 +1124,7 @@ fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result merge_channels_ui::confirm(app, &d.fields), _ if crate::analysis_ui::owns_delete_note(&d.fields) => crate::analysis_ui::confirm_delete_note(app, &d.fields), + _ if crate::analysis_ui::owns_clear_notes(&d.fields) => crate::analysis_ui::confirm_clear_notes(app, &d.fields), _ if crate::file_ui::owns(&d.fields) => crate::file_ui::confirm(app, &d.fields), _ if crate::new_guide_ui::owns(&d.fields) => crate::new_guide_ui::confirm(app, &d.fields), _ if crate::color_picker_ui::owns(&d.fields) => { @@ -1151,13 +1157,18 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { } DialogKind::Command => confirm_command(app, d), DialogKind::LayerStyle => crate::layer_style::confirm(app, &d.fields), - DialogKind::About | DialogKind::Error => Ok(Value::Null), + DialogKind::About => Ok(Value::Null), + DialogKind::Error => { + dont_show_again::closed(app, &d); + Ok(Value::Null) + } } } /// Cancel a dialog and its dependent Layer Style picker, without applying edits. pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result { let closed = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?; + dont_show_again::closed(app, &closed); crate::guide_edit::cancel(app, id); // A Color Picker puts back what its live preview showed in its target. crate::color_picker_ui::live_preview::end(app, id); @@ -1264,6 +1275,7 @@ pub mod dialog_blend_ui; pub mod discard_ui; pub mod disk_change_prompt; pub mod distort_ui; +pub mod dont_show_again; pub mod duplicate_layer_ui; pub mod edit_history; pub mod equalize_ui; diff --git a/crates/ui-egui/src/dialogs/adjust_editors.rs b/crates/ui-egui/src/dialogs/adjust_editors.rs index c3062fdb7c..c1624fe3c9 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors.rs @@ -47,7 +47,7 @@ use gradient_map::gradient_map; pub use gradient_map::{gradient_presets, is_gray, swatches}; use hue_saturation::hue_saturation; #[cfg(test)] -use hue_saturation::{lightness_track, move_hue_range_handle, saturation_track}; +use hue_saturation::{hue_range_handle_at, hue_range_zone, lightness_track, move_hue_range_handle, move_hue_range_zone, saturation_track}; use levels::levels; pub(crate) use levels::levels_drag; pub use levels::{auto_levels, gamma_from_pos, gamma_pos}; @@ -273,6 +273,53 @@ mod tests { assert_eq!(track_stops(&cx(false), &stops), None); } + /// #9272 review: at the narrowest Properties panel (a 230-point bar) a 30° zone is ~19 points + /// wide; a press in its middle grabs the zone, not a handle, while each handle stays grabbable. + #[test] + fn hue_range_zones_stay_selectable_on_a_narrow_bar() { + let w = 230.0; + let xs = [75.0f32, 105.0, 135.0, 165.0].map(|d| d / 360.0 * w); + for (a, z) in [(0, 1), (1, 2), (2, 3)] { + assert_eq!(hue_range_handle_at(xs, (xs[a] + xs[z]) / 2.0, w), None, "the middle of zone {a}..{z} is the zone's"); + } + for (k, x) in xs.iter().enumerate() { + assert_eq!(hue_range_handle_at(xs, *x + 1.0, w), Some(k as u8), "handle {k}"); + } + assert_eq!(hue_range_handle_at(xs, xs[0] - 9.0, w), Some(0), "the full reach outside the range"); + let stacked = [50.0, 50.0, 80.0, 120.0]; + assert!(hue_range_handle_at(stacked, 51.0, w).is_some(), "coinciding handles stay grabbable"); + // Reds (315/345…15\45): its fully-on zone crosses the seam, ~9.6 points from each edge. + let reds = [315.0f32, 345.0, 15.0, 45.0].map(|d| d / 360.0 * w); + for x in [w - 1.0, w - 3.0, 0.5, 2.5] { + assert_eq!(hue_range_handle_at(reds, x, w), None, "x {x}: Reds' fully-on zone across the seam"); + } + assert_eq!(hue_range_handle_at(reds, reds[1] + 1.0, w), Some(1)); + assert_eq!(hue_range_handle_at(reds, reds[2] - 1.0, w), Some(2)); + } + + /// #9252: Photoshop 2025's zone drags on a colour range (measured on Reds): the fully-on span + /// moves all four handles, each fade its own two; a side stops at the other and the range + /// never passes a turn. + #[test] + fn hue_range_zones_move_their_handles() { + let reds = [-45.0, -15.0, 15.0, 45.0]; + assert_eq!(hue_range_zone(reds, 345.0 - 15.0), Some(0)); + assert_eq!(hue_range_zone(reds, 0.0), Some(1)); + assert_eq!(hue_range_zone(reds, 30.0), Some(2)); + assert_eq!(hue_range_zone(reds, 180.0), None); + let centre = move_hue_range_zone(reds, 1, 37.0); + assert_eq!(centre, [-8.0, 22.0, 52.0, 82.0], "all four, as Photoshop's 315/345…15\\45 → 352/21…52\\81"); + let left = move_hue_range_zone(centre, 0, -19.0); + assert_eq!(left, [-27.0, 3.0, 52.0, 82.0], "the left two only"); + let right = move_hue_range_zone(left, 2, 19.0); + assert_eq!(right, [-27.0, 3.0, 71.0, 101.0], "the right two only"); + assert_eq!(move_hue_range_zone(reds, 0, 100.0), [-15.0, 15.0, 15.0, 45.0], "the left side stops at the right"); + assert_eq!(move_hue_range_zone(reds, 2, -100.0), [-45.0, -15.0, -15.0, 15.0], "and the right at the left"); + let wide = move_hue_range_zone(reds, 2, 500.0); + assert!(wide[3] - wide[0] <= 359.0 + 1e-3, "{wide:?}"); + assert_eq!(move_hue_range_zone(reds, 1, f32::NAN), reds); + } + #[test] fn hue_range_drag_canonicalizes_bounds_before_clamping() { let moved = move_hue_range_handle([0.0, 350.0, 100.0, 200.0], 2, 354.0); diff --git a/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs b/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs index 70413d0440..fcd829d424 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/gradient_map.rs @@ -180,38 +180,33 @@ pub(super) fn gradient_map(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> E label(ui, tl!("Preset:")); let mut picked = None; let (press, close) = crate::press_menu::PressCombo::before(ui, cx.mem.with("gm-preset")); - let combo = craft_ui::ComboBox::from_id_salt(cx.mem.with("gm-preset")) - .selected_text(tl!("Custom")) - .width(ui.available_width().min(190.0)) - .height(420.0) - .icon(widgets::chevron_icon) - .close_behavior(close) - .show_ui(ui, |ui| { - let gear = crate::icons::button(ui, "settings", 24.0, false, tl!("Gradient Preset Options")); - egui::containers::menu::SubMenu::new().show(ui, &gear, |ui| { - if ui.button(tl!("Import .GRD")).clicked() { - e.import_gradients = true; - ui.close(); - } - }); - ui.separator(); - for g in &cx.gradients { - ui.label(RichText::new(&g.name).color(t.text_faint)); - for p in &g.items { - ui.horizontal(|ui| { - // A map has no transparency: colour stops only, shown opaque. - let rgba: Vec<(f32, [f32; 4])> = p.resolve(fg, bg).into_iter().map(|(at, c)| (at, [c[0], c[1], c[2], 1.0])).collect(); - let (r, swatch) = ui.allocate_exact_size(vec2(48.0, 16.0), Sense::click()); - crate::preset_panels::paint_gradient(ui, r, &rgba); - // Both, not short-circuited: the name is drawn either way. - let name = ui.selectable_label(false, &p.name); - if press.chosen(ui, &swatch) | press.chosen(ui, &name) { - picked = Some(rgba.iter().map(|(at, c)| (*at, [c[0], c[1], c[2]])).collect::>()); - } - }); - } + let width = ui.available_width().min(190.0); + let combo = widgets::combo_list(ui, cx.mem.with("gm-preset"), tl!("Custom"), width, close, |ui| { + let gear = crate::icons::button(ui, "settings", 24.0, false, tl!("Gradient Preset Options")); + egui::containers::menu::SubMenu::new().show(ui, &gear, |ui| { + if ui.button(tl!("Import .GRD")).clicked() { + e.import_gradients = true; + ui.close(); } }); + ui.separator(); + for g in &cx.gradients { + ui.label(RichText::new(&g.name).color(t.text_faint)); + for p in &g.items { + ui.horizontal(|ui| { + // A map has no transparency: colour stops only, shown opaque. + let rgba: Vec<(f32, [f32; 4])> = p.resolve(fg, bg).into_iter().map(|(at, c)| (at, [c[0], c[1], c[2], 1.0])).collect(); + let (r, swatch) = ui.allocate_exact_size(vec2(48.0, 16.0), Sense::click()); + crate::preset_panels::paint_gradient(ui, r, &rgba); + // Both, not short-circuited: the name is drawn either way. + let name = ui.selectable_label(false, &p.name); + if press.chosen(ui, &swatch) | press.chosen(ui, &name) { + picked = Some(rgba.iter().map(|(at, c)| (*at, [c[0], c[1], c[2]])).collect::>()); + } + }); + } + } + }); press.after(&combo.response); let _ = combo.response.accessible_name(tl!("Preset:")); if let Some(p) = picked { diff --git a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs index b1c61947fa..29393a4031 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/hue_saturation.rs @@ -38,6 +38,62 @@ pub(super) fn move_hue_range_handle(bounds: [f32; 4], k: usize, deg: f32) -> [f3 b } +/// The range handle a press at `x` grabs, given the four handles' x positions on a bar `w` wide: +/// the nearest within 10 points, or within a third of the gap to the next handle on that side, so +/// the middle third of a narrow zone still drags the zone (at least 3 points, for handles that +/// coincide). The bar is a hue circle: the next handle past an edge is the first from the other. +pub(super) fn hue_range_handle_at(xs: [f32; 4], x: f32, w: f32) -> Option { + let k = nearest(&xs, x)?; + let (xk, d) = (xs[k as usize], x - xs[k as usize]); + let gap = xs + .iter() + .enumerate() + .filter(|&(j, _)| j != k as usize) + .map(|(_, &o)| if d >= 0.0 { (o - xk).rem_euclid(w) } else { (xk - o).rem_euclid(w) }) + .fold(f32::INFINITY, f32::min); + (d.abs() < (gap / 3.0).clamp(3.0, 10.0)).then_some(k) +} + +/// Which zone of a colour range a hue `deg` falls in, between its handles: 0 = the left fade +/// (between the first two), 1 = the fully-on span, 2 = the right fade; `None` outside the range. +pub(super) fn hue_range_zone(bounds: [f32; 4], deg: f32) -> Option { + let b = HueRange::canonical_bounds(bounds); + let rel = (deg - b[0]).rem_euclid(360.0); + let (one, two, three) = (b[1] - b[0], b[2] - b[0], b[3] - b[0]); + if rel <= one { + Some(0) + } else if rel <= two { + Some(1) + } else if rel <= three { + Some(2) + } else { + None + } +} + +/// A drag of `delta` degrees on a zone of a colour range (#9252), as in Photoshop: the left fade +/// moves the two left handles, the fully-on span all four, the right fade the two right handles; +/// a side never crosses the other or grows the range past a turn. +pub(super) fn move_hue_range_zone(start: [f32; 4], zone: u8, delta: f32) -> [f32; 4] { + let b = HueRange::canonical_bounds(start); + if !delta.is_finite() { + return b; + } + let moved = match zone { + 0 => { + let d = delta.min(b[2] - b[1]).max(b[3] - 359.0 - b[0]); + [b[0] + d, b[1] + d, b[2], b[3]] + } + 1 => b.map(|v| v + delta), + 2 => { + let d = delta.max(b[1] - b[2]).min(b[0] + 359.0 - b[3]); + [b[0], b[1], b[2] + d, b[3] + d] + } + _ => b, + }; + HueRange::canonical_bounds(moved) +} + /// The spectrum bar after the adjustment (what each hue becomes), sampled at `n` hues. fn adjusted_spectrum(v: &Value, n: usize) -> Vec { let adj = photocraft_engine::commands::adjustment_from_params("hueSaturation", v); @@ -177,17 +233,44 @@ pub(super) fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> p.rect_filled(Rect::from_center_size(pos2(x, mid), vec2(5.0, 12.0)), 1.0, fill); p.rect_stroke(Rect::from_center_size(pos2(x, mid), vec2(5.0, 12.0)), 1.0, Stroke::new(1.0, t.text_dim), StrokeKind::Inside); } + ui.data_mut(|d| d.insert_temp(cx.mem.with("hs-range-bars"), bars)); let drag_id = cx.mem.with("hs-range-drag"); + let zone_id = cx.mem.with("hs-range-zone"); let mut which: Option = ui.data(|d| d.get_temp(drag_id)).flatten(); + // A press between the handles drags a zone (#9252): its zone, the bounds and x it began at. + let mut zone: Option<(u8, [f32; 4], f32)> = ui.data(|d| d.get_temp(zone_id)).flatten(); if bresp.is_pointer_button_down_on() && ui.input(|i| i.pointer.primary_pressed()) && let Some(pos) = ui.input(|i| i.pointer.press_origin()) { - which = nearest(&b.map(xof), pos.x).filter(|k| (xof(b[*k as usize]) - pos.x).abs() < 10.0); + which = hue_range_handle_at(b.map(xof), pos.x, w); + zone = if which.is_none() { hue_range_zone(b, deg_of(pos.x)).map(|z| (z, b, pos.x)) } else { None }; } - if bresp.is_pointer_button_down_on() - && let (Some(k), Some(pos)) = (which, ui.input(|i| i.pointer.interact_pos())) - { + // The release frame applies its position too: a move and a release that land in one frame + // would otherwise commit the bounds from before the move. It ends where the button let go, + // not where the pointer went after that in the same frame. + let released_at = ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => Some(*pos), + _ => None, + }) + }); + let live = bresp.is_pointer_button_down_on() || released_at.is_some(); + let drag_pos = released_at.or_else(|| ui.input(|i| i.pointer.interact_pos())); + if live && let (Some((z, start, x0)), Some(pos)) = (zone, drag_pos) { + let before = b; + b = move_hue_range_zone(start, z, (pos.x - x0) / w * 360.0); + if b != before { + v[key]["range"] = json!(b.map(|x| x.round())); + e.changed = true; + } + } + if zone.is_some() && !bresp.is_pointer_button_down_on() { + zone = None; + e.commit = true; + } + ui.data_mut(|d| d.insert_temp(zone_id, zone)); + if live && let (Some(k), Some(pos)) = (which, drag_pos) { let k = k as usize; let deg = deg_of(pos.x); let before = b; diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index 7e21fc91fc..81b5dba8cb 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -661,6 +661,57 @@ fn gradient_map_strip_adds_selects_and_removes_stops_without_deleting_the_last_p assert_eq!(layer(&h).1, original, "keep two stops"); } +/// #10742: a Gradient Map stop dragged down off the bar is removed on release (one history step); +/// while it is off the bar the live preview already leaves it out, and dragging it back onto the +/// bar before release puts it back. The last two stops can't be dragged off. +#[test] +fn gradient_map_stop_dragged_down_off_the_bar_is_removed_and_dragging_back_cancels() { + let mut h = app_harness("gradientMap", "rgb", 8); + let (id, _) = layer(&h); + h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "stops": [[0, "#000000"], [0.5, "#ff0000"], [1, "#ffffff"]]})).unwrap(); + h.run_steps(3); + let three = layer(&h).1; + let before_cancel = h.state().session.active().unwrap().history.past_len(); + let live_stops = |h: &Harness<'_, PhotocraftApp>| h.state().live_adjust.as_ref().and_then(|(_, v)| v["stops"].as_array().map(Vec::len)); + // Off and back: nothing removed. + let start = map_handle(&h, 0.5); + let away = start + vec2(0.0, 30.0); + h.hover_at(start); + h.run_steps(1); + h.drag_at(start); + h.run_steps(1); + h.hover_at(start + vec2(0.0, 15.0)); + h.run_steps(1); + h.hover_at(away); + h.run_steps(1); + assert_eq!(live_stops(&h), Some(2), "off the bar the preview leaves the stop out"); + h.hover_at(start); + h.run_steps(1); + assert_eq!(live_stops(&h), Some(3), "back on the bar the stop returns"); + h.drop_at(start); + h.run_steps(3); + assert_eq!(map_stops(&layer(&h).1), map_stops(&three), "dragging back cancels the removal"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), before_cancel, "a cancelled drag adds no history step"); + // Off and released: removed in one step. + let steps = h.state().session.active().unwrap().history.past_len(); + drag(&mut h, start, away); + assert_eq!(map_stops(&layer(&h).1), vec![(0.0, [0, 0, 0]), (1.0, [255, 255, 255])]); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); + assert!(h.state().live_adjust.is_none()); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(layer(&h).1, three); + h.state_mut().run("edit.redo", json!({})).unwrap(); + h.run_steps(3); + // Two stops stay. + let two = layer(&h).1; + for at in [0.0, 1.0] { + let from = map_handle(&h, at); + drag(&mut h, from, from + vec2(0.0, 40.0)); + assert_eq!(map_stops(&layer(&h).1), map_stops(&two), "two stops always remain"); + } +} + #[test] fn gradient_map_drag_clamps_at_the_endpoints_and_reverse_keeps_stop_coordinates() { let mut h = app_harness("gradientMap", "rgb", 8); @@ -1097,6 +1148,138 @@ fn gradient_map_stop_picker_closed_without_a_colour_changes_nothing() { } } +/// #9252: in a Hue/Saturation layer's Properties, dragging the zones between the range handles +/// moves them as Photoshop does: the fully-on span all four, a fade its own two; one history step +/// per drag. +#[test] +fn hue_saturation_range_zones_drag_their_handles() { + let mut h = app_harness("hueSaturation", "rgb", 8); + let (id, _) = layer(&h); + let mem = crate::adjust_editors::layer_mem(id); + h.ctx.data_mut(|d| d.insert_temp(mem.with("hs-range"), 3usize)); // Greens: 75/105…135\165 + h.run_steps(3); + let bars: Rect = h.ctx.data(|d| d.get_temp(mem.with("hs-range-bars"))).expect("the range bars"); + let x = |deg: f32| bars.left() + deg / 360.0 * bars.width(); + let y = bars.center().y; + let greens = |h: &Harness<'_, PhotocraftApp>| match layer(h).1 { + Adjustment::HueSaturation { ranges, .. } => ranges[2].bounds, + other => panic!("{other:?}"), + }; + let steps = h.state().session.active().unwrap().history.past_len(); + drag(&mut h, Pos2::new(x(120.0), y), Pos2::new(x(156.0), y)); + let b = greens(&h); + assert!((b[0] - 111.0).abs() <= 1.0 && (b[3] - 201.0).abs() <= 1.0 && (b[1] - b[0] - 30.0).abs() < 0.5, "all four moved ~36°: {b:?}"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one step"); + let before = greens(&h); + drag(&mut h, Pos2::new(x((before[0] + before[1]) / 2.0), y), Pos2::new(x((before[0] + before[1]) / 2.0 - 18.0), y)); + let b = greens(&h); + assert!((b[0] - (before[0] - 18.0)).abs() <= 1.0 && (b[1] - (before[1] - 18.0)).abs() <= 1.0, "left two moved: {before:?} → {b:?}"); + assert_eq!([b[2], b[3]], [before[2], before[3]], "right two stay"); +} + +/// CodeRabbit on #9272: a move and release that land in the same frame still move the zone; the +/// release frame applies its position before the drag commits. +#[test] +fn a_zone_drag_released_in_the_frame_it_moves_still_moves() { + let mut h = app_harness("hueSaturation", "rgb", 8); + let (id, _) = layer(&h); + let mem = crate::adjust_editors::layer_mem(id); + h.ctx.data_mut(|d| d.insert_temp(mem.with("hs-range"), 3usize)); // Greens: 75/105…135\165 + h.run_steps(3); + let bars: Rect = h.ctx.data(|d| d.get_temp(mem.with("hs-range-bars"))).expect("the range bars"); + let x = |deg: f32| bars.left() + deg / 360.0 * bars.width(); + let y = bars.center().y; + let steps = h.state().session.active().unwrap().history.past_len(); + let (from, to) = (Pos2::new(x(120.0), y), Pos2::new(x(156.0), y)); + h.hover_at(from); + h.run_steps(1); + h.drag_at(from); + h.run_steps(1); + // One frame: the pointer moves and lets go (the harness's queued events take a frame each, + // so both go straight into the next frame's input). + let events = &mut h.input_mut().events; + events.push(egui::Event::PointerMoved(to)); + events.push(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); + let b = match layer(&h).1 { + Adjustment::HueSaturation { ranges, .. } => ranges[2].bounds, + other => panic!("{other:?}"), + }; + assert!((b[0] - 111.0).abs() <= 1.0 && (b[3] - 201.0).abs() <= 1.0, "all four moved ~36°: {b:?}"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one step"); + // A handle released in the frame it moves lands there too. + let (from, to) = (Pos2::new(x(b[3]), y), Pos2::new(x(b[3] + 20.0), y)); + h.hover_at(from); + h.run_steps(1); + h.drag_at(from); + h.run_steps(1); + let events = &mut h.input_mut().events; + events.push(egui::Event::PointerMoved(to)); + events.push(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); + let after = match layer(&h).1 { + Adjustment::HueSaturation { ranges, .. } => ranges[2].bounds, + other => panic!("{other:?}"), + }; + assert!((after[3] - (b[3] + 20.0)).abs() <= 1.0 && after[..3] == b[..3], "the right handle moved 20°: {b:?} → {after:?}"); + // A release followed by more movement in one frame ends where the button let go. + let b = after; + let (from, to) = (Pos2::new(x((b[1] + b[2]) / 2.0), y), Pos2::new(x((b[1] + b[2]) / 2.0 + 10.0), y)); + h.hover_at(from); + h.run_steps(1); + h.drag_at(from); + h.run_steps(1); + let events = &mut h.input_mut().events; + events.push(egui::Event::PointerMoved(to)); + events.push(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + events.push(egui::Event::PointerMoved(Pos2::new(x(b[3] + 60.0), y))); + h.run_steps(3); + let last = match layer(&h).1 { + Adjustment::HueSaturation { ranges, .. } => ranges[2].bounds, + other => panic!("{other:?}"), + }; + assert!(last.iter().zip(&b).all(|(l, b)| (l - (b + 10.0)).abs() <= 1.0), "moved 10° to the release, not past it: {b:?} → {last:?}"); +} + +/// FredApps review on #9272: a zone drag across the 0/360 seam. Reds' fully-on span sits on both +/// ends of the bar; a drag from its middle third at either end (nearer a handle grabs the handle) +/// moves the whole range intact, and the handles that pass the seam come out at the other end. +#[test] +fn hue_saturation_range_zone_drags_across_the_seam() { + let mut h = app_harness("hueSaturation", "rgb", 8); + let (id, _) = layer(&h); + let mem = crate::adjust_editors::layer_mem(id); + h.ctx.data_mut(|d| d.insert_temp(mem.with("hs-range"), 1usize)); // Reds: 315/345…15\45 + h.run_steps(3); + let bars: Rect = h.ctx.data(|d| d.get_temp(mem.with("hs-range-bars"))).expect("the range bars"); + let x = |deg: f32| bars.left() + deg / 360.0 * bars.width(); + let y = bars.center().y; + let reds = |h: &Harness<'_, PhotocraftApp>| match layer(h).1 { + Adjustment::HueSaturation { ranges, .. } => ranges[0].bounds, + other => panic!("{other:?}"), + }; + let on_circle = |b: [f32; 4]| b.map(|d| d.rem_euclid(360.0).round()); + let widths = |b: [f32; 4]| [b[1] - b[0], b[2] - b[1], b[3] - b[2]]; + let mut steps = h.state().session.active().unwrap().history.past_len(); + // (press, release, where the four handles land on the circle) + for (from, to, want) in [ + // The span's right end, dragged left: 15\45 cross the seam to the right end. + (358.0, 298.0, [255.0, 285.0, 315.0, 345.0]), + // Back right from its middle: 315\345 cross the seam to the left end. + (300.0, 360.0, [315.0, 345.0, 15.0, 45.0]), + // The span's left end, dragged right: 315/345 cross the seam to the left end. + (2.0, 62.0, [15.0, 45.0, 75.0, 105.0]), + ] { + let before = reds(&h); + drag(&mut h, Pos2::new(x(from), y), Pos2::new(x(to), y)); + let b = reds(&h); + assert!(on_circle(b).iter().zip(&want).all(|(d, w)| (d - w).abs() <= 1.0), "{from}° → {to}°: {before:?} → {b:?}, want {want:?}"); + assert_eq!(widths(b), widths(before), "{from}° → {to}°: the range moves intact"); + steps += 1; + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps, "{from}° → {to}°: one step"); + } +} + /// Selective Color in Properties: the Colors dropdown's choice lives in editor memory, so /// switching colour commits nothing, and each colour keeps its own row. #[test] diff --git a/crates/ui-egui/src/dialogs/camera_raw_detail_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_detail_ui.rs index 88747a8dd7..008eaf723a 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_detail_ui.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_detail_ui.rs @@ -75,7 +75,7 @@ impl DetailPreview { let result = match rx.try_recv() { Ok(result) => result, Err(TryRecvError::Empty) => return, - Err(TryRecvError::Disconnected) => Err("Camera Raw detail preview worker stopped".into()), + Err(TryRecvError::Disconnected) => Err("RAW Develop detail preview worker stopped".into()), }; self.pending = None; match result { @@ -104,7 +104,7 @@ impl DetailPreview { // The engine's full-image pipeline needs multiple temporary float buffers. Never start // an unbounded allocation just because a huge sparse document was zoomed into. if self.area.width() as u64 * self.area.height() as u64 > 64_000_000 { - self.error = Some("Full-resolution Camera Raw preview is limited to 64 megapixels; the proxy remains available".into()); + self.error = Some("Full-resolution RAW Develop preview is limited to 64 megapixels; the proxy remains available".into()); self.failed_revision = Some(revision); return; } @@ -124,7 +124,7 @@ impl DetailPreview { let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| develop(&source, raw_curve.as_deref().map(Vec::as_slice), area, ¶ms, &coverage))) .map(|surface| (revision, surface)) - .map_err(|_| "Camera Raw detail preview failed; the proxy remains available".into()); + .map_err(|_| "RAW Develop detail preview failed; the proxy remains available".into()); if !cancel.load(Ordering::Relaxed) { let _ = tx.send(result); ctx.request_repaint(); @@ -141,7 +141,7 @@ impl DetailPreview { }) { Ok(_) => self.pending = Some((revision, rx)), Err(e) => { - self.error = Some(format!("Cannot start Camera Raw preview: {e}")); + self.error = Some(format!("Cannot start RAW Develop preview: {e}")); self.failed_revision = Some(revision); } } @@ -152,7 +152,7 @@ impl DetailPreview { // instead of blocking its UI with the full-image engine pipeline. drop(work); drop(rx); - self.error = Some("Full-resolution filtered preview requires a native Camera Raw worker; the web preview keeps the proxy".into()); + self.error = Some("Full-resolution filtered preview requires a native RAW Develop worker; the web preview keeps the proxy".into()); self.failed_revision = Some(revision); } } diff --git a/crates/ui-egui/src/dialogs/camera_raw_gpu.rs b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs index 5e9f8719fa..f4545a5bb1 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_gpu.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_gpu.rs @@ -32,11 +32,11 @@ impl Pass { return false; } if adapter.get_info().device_type == wgpu::DeviceType::Cpu { - log::info!("Camera Raw develops on the CPU: software graphics adapter"); + log::info!("RAW Develop develops on the CPU: software graphics adapter"); return false; } if !CameraRawDevelop::supported(adapter) { - log::info!("Camera Raw develops on the CPU: the adapter can't render Rgba32Float"); + log::info!("RAW Develop develops on the CPU: the adapter can't render Rgba32Float"); return false; } true @@ -53,7 +53,7 @@ impl Pass { let (on, out) = (device.clone(), slot.clone()); let spawned = std::thread::Builder::new().name("camera-raw-pipeline".into()).spawn(move || { let pass = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Self::build_on(&on))).unwrap_or_else(|_| { - log::warn!("building the Camera Raw pipeline panicked; Camera Raw develops on the CPU"); + log::warn!("building the RAW Develop pipeline panicked; RAW Develop develops on the CPU"); None }); let _ = out.set(pass); @@ -70,7 +70,7 @@ impl Pass { match CameraRawDevelop::new(device) { Ok(pass) => Some(Pass(Arc::new(Mutex::new(pass)))), Err(e) => { - log::warn!("{e}; Camera Raw develops on the CPU"); + log::warn!("{e}; RAW Develop develops on the CPU"); None } } @@ -140,7 +140,7 @@ impl CameraRawGpu { match pass.develop(&self.device, &self.queue, Some(&self.health), px, key, size, &stages) { Ok(out) => Some(out), Err(e) => { - log::warn!("{}; Camera Raw develops on the CPU", e.0); + log::warn!("{}; RAW Develop develops on the CPU", e.0); self.failed.store(true, Ordering::Relaxed); None } @@ -215,7 +215,7 @@ mod tests { let _gpu = photocraft_testkit::gpu_lock(); let Some((mut app, ctx)) = gpu_app(8) else { return }; let canvas = app.gpu.clone().expect("GPU canvas"); - assert!(!canvas.camera_raw_started(), "no Camera Raw pipeline at launch (#6419)"); + assert!(!canvas.camera_raw_started(), "no RAW Develop pipeline at launch (#6419)"); crate::camera_raw_ui::open(&mut app, &ctx).unwrap(); assert!(canvas.camera_raw_started(), "built (or refused) from the first open"); assert_eq!(app.camera_raw.as_ref().map(|d| d.develop_backend), Some("cpu"), "the first frame doesn't wait for the pipeline"); @@ -233,7 +233,7 @@ mod tests { force_pass(&app); crate::camera_raw_ui::open(&mut app, &ctx).unwrap(); if app.camera_raw.as_ref().is_some_and(|d| d.gpu.is_none()) { - eprintln!("skipping: the device can't run the Camera Raw pass"); + eprintln!("skipping: the device can't run the RAW Develop pass"); return; } let per_pixel = CameraRaw { @@ -272,7 +272,7 @@ mod tests { force_pass(&app); crate::camera_raw_ui::open(&mut app, &ctx).unwrap(); if app.camera_raw.as_ref().is_some_and(|d| d.gpu.is_none()) { - eprintln!("skipping: the device can't run the Camera Raw pass"); + eprintln!("skipping: the device can't run the RAW Develop pass"); return; } let (backend, _, _) = developed(&mut app, &ctx, CameraRaw { exposure: 0.5, ..Default::default() }); diff --git a/crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs index dff92fd50e..91242a13a0 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_preview_ui.rs @@ -56,7 +56,7 @@ impl CameraRawPreviewState { /// Validate with the rest of the Camera Raw request before changing anything. pub(crate) fn prepare(current: CameraRawPreviewState, value: &Value) -> Result { - let obj = value.as_object().ok_or("Camera Raw view must be an object")?; + let obj = value.as_object().ok_or("RAW Develop view must be an object")?; let mut next = current; for (key, value) in obj { match key.as_str() { @@ -65,22 +65,22 @@ pub(crate) fn prepare(current: CameraRawPreviewState, value: &Value) -> Result { - let a = value.as_array().filter(|a| a.len() == 2).ok_or("Camera Raw center must be [u,v]")?; + let a = value.as_array().filter(|a| a.len() == 2).ok_or("RAW Develop center must be [u,v]")?; let coordinate = |i| { a.get(i) .and_then(Value::as_f64) .filter(|v| v.is_finite() && (0.0..=1.0).contains(v)) .map(|v| v as f32) - .ok_or("Camera Raw center must be finite coordinates in 0–1") + .ok_or("RAW Develop center must be finite coordinates in 0–1") }; next.center = [coordinate(0)?, coordinate(1)?]; } - "hand" => next.hand = value.as_bool().ok_or("Camera Raw hand must be a boolean")?, - _ => return Err(format!("unknown Camera Raw view property {key}")), + "hand" => next.hand = value.as_bool().ok_or("RAW Develop hand must be a boolean")?, + _ => return Err(format!("unknown RAW Develop view property {key}")), } } if obj.get("zoom").and_then(Value::as_str) == Some("fit") { diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui.rs b/crates/ui-egui/src/dialogs/camera_raw_ui.rs index c32240b4cb..3c2f576671 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui.rs @@ -247,7 +247,7 @@ impl CameraRawDialog { let (tx, rx) = std::sync::mpsc::channel::>(); let repaint = ctx.clone(); let spawned = std::thread::Builder::new().name("camera-raw-proxy".into()).spawn(move || { - let frame = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run())).map_err(|_| "Camera Raw preview failed".to_string()); + let frame = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run())).map_err(|_| "RAW Develop preview failed".to_string()); // The dialog may have closed or rendered on its own meanwhile; then nobody listens. if tx.send(frame).is_ok() { repaint.request_repaint(); @@ -273,7 +273,7 @@ impl CameraRawDialog { let frame = match rx.try_recv() { Ok(frame) => frame, Err(std::sync::mpsc::TryRecvError::Empty) => return Ok(()), - Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("Camera Raw preview worker stopped".to_string()), + Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("RAW Develop preview worker stopped".to_string()), }; self.pending = None; self.publish(ctx, frame?); diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs index d764ad987f..b3a1792c9f 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs @@ -49,7 +49,7 @@ fn history_keys(d: &mut CameraRawDialog, ctx: &egui::Context) { } pub(super) fn commit(app: &mut PhotocraftApp) -> Result { - let d = app.camera_raw.as_ref().ok_or(tl!("Camera Raw isn't open"))?; + let d = app.camera_raw.as_ref().ok_or(tl!("RAW Develop isn't open"))?; let result = match d.target { Target::NewFilter => { let mut p = d.command_params(); @@ -225,12 +225,12 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } impl CameraRawDialog { - /// "Camera Raw (name)" for the open-time dialog, "Camera Raw Filter (layer)" otherwise. + /// "RAW Develop (name)" for the open-time dialog, "RAW Develop Filter (layer)" otherwise. fn window_title(&self) -> String { if self.target == Target::OpenRaw { - crate::i18n::fmt(tl!("Camera Raw ({name})"), &[("name", &self.layer_name)]) + crate::i18n::fmt(tl!("RAW Develop ({name})"), &[("name", &self.layer_name)]) } else { - crate::i18n::fmt(tl!("Camera Raw Filter ({layer})"), &[("layer", &self.layer_name)]) + crate::i18n::fmt(tl!("RAW Develop Filter ({layer})"), &[("layer", &self.layer_name)]) } } } diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs index 313110eaca..a3d146a7fb 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs @@ -56,11 +56,11 @@ pub(super) fn preview_area(canvas: Rect, surf: &photocraft_raster::Surface) -> R let width = area.x1.checked_sub(area.x0).filter(|n| (1..=1_048_576).contains(n)); let height = area.y1.checked_sub(area.y0).filter(|n| (1..=1_048_576).contains(n)); let (Some(w), Some(h)) = (width, height) else { - return Err("Camera Raw preview bounds are too large".into()); + return Err("RAW Develop preview bounds are too large".into()); }; let (w, h) = (w as usize, h as usize); if w.checked_mul(h).is_none_or(|pixels| pixels > 512_000_000) { - return Err("Camera Raw preview bounds are too large".into()); + return Err("RAW Develop preview bounds are too large".into()); } Ok((area, w, h)) } diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/filmstrip.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/filmstrip.rs index 1e35869dbe..85f37f2d6a 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/filmstrip.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/filmstrip.rs @@ -213,7 +213,7 @@ pub(super) fn done(app: &mut PhotocraftApp) -> Value { return json!({"done": false, "saved": saved}); } app.ui.status = if !saved.is_empty() { - crate::i18n::fmt(tl!("Saved Camera Raw settings to {file}"), &[("file", &saved.iter().map(|s| s.as_str()).collect::>().join(", "))]) + crate::i18n::fmt(tl!("Saved RAW Develop settings to {file}"), &[("file", &saved.iter().map(|s| s.as_str()).collect::>().join(", "))]) } else if stored.iter().all(|s| *s == Stored::Defaults) { tl!("Nothing to save: these raws are at their default settings").to_string() } else { diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs index b8c75a94e1..968112d5f5 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs @@ -54,6 +54,7 @@ fn identity_app() -> (PhotocraftApp, RawOpen, Control) { bytes: Some(bytes), developed_with: Default::default(), demosaic: Default::default(), + crop: None, }; let mut app = PhotocraftApp::new(session, crate::Services::default()); app.sync_views(); @@ -103,7 +104,7 @@ fn completion_identity_applies_remaining_settings_after_tab_reordering() { let state = app.session.active().unwrap(); assert_eq!(state.doc.id, replacement); assert!(!state.is_dirty(), "development finishes opening only the replacement"); - assert!(state.history.past_len() > 0, "remaining Camera Raw settings were applied"); + assert!(state.history.past_len() > 0, "remaining RAW Develop settings were applied"); assert!(!app.view_docs.contains(&raw.document)); assert!(app.view_docs.contains(&replacement)); } diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/menu.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/menu.rs index 8aed0e5664..3ee43b9ca2 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/menu.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/menu.rs @@ -9,7 +9,7 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val return None; } let Some(fields) = params.as_object() else { - return Some(Err("Camera Raw params must be an object".into())); + return Some(Err("RAW Develop params must be an object".into())); }; if fields.is_empty() { return Some( @@ -30,26 +30,26 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val } let ui = params.get("ui")?; let Some(fields) = ui.as_object() else { - return Some(Err("Camera Raw ui must be an object".into())); + return Some(Err("RAW Develop ui must be an object".into())); }; for (key, value) in fields { match key.as_str() { "set" | "scope" | "view" | "demosaic" => {} "before" | "commit" | "cancel" | "done" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" if value.is_boolean() => {} "before" | "commit" | "cancel" | "done" | "saveSettings" | "loadSettings" | "undo" | "redo" | "auto" => { - return Some(Err(format!("Camera Raw {key} must be a boolean"))); + return Some(Err(format!("RAW Develop {key} must be a boolean"))); } - _ => return Some(Err(format!("unknown Camera Raw ui property {key}"))), + _ => return Some(Err(format!("unknown RAW Develop ui property {key}"))), } } let ends = ["commit", "cancel", "done"].into_iter().filter(|k| ui.get(*k).and_then(Value::as_bool) == Some(true)).count(); if ends > 1 { - return Some(Err("Camera Raw takes one of commit, cancel and done".into())); + return Some(Err("RAW Develop takes one of commit, cancel and done".into())); } for (key, run) in [("saveSettings", save_settings as fn(&mut PhotocraftApp) -> Result), ("loadSettings", load_settings)] { if ui.get(key).and_then(Value::as_bool) == Some(true) { if fields.len() > 1 { - return Some(Err(format!("Camera Raw {key} must be sent on its own"))); + return Some(Err(format!("RAW Develop {key} must be sent on its own"))); } return Some(run(app)); } @@ -83,23 +83,23 @@ fn menu_update(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &Value) -> Opti } if let Some(set) = ui.get("set") { if !set.is_object() { - return Some(Err("bad Camera Raw settings: expected an object".into())); + return Some(Err("bad RAW Develop settings: expected an object".into())); } let mut cur = serde_json::to_value(&d.params).unwrap_or(json!({})); if let (Value::Object(c), Value::Object(s)) = (&mut cur, set) { for (k, v) in s { if !c.contains_key(k) { - return Some(Err(format!("unknown Camera Raw setting {k}"))); + return Some(Err(format!("unknown RAW Develop setting {k}"))); } c.insert(k.clone(), v.clone()); } } next_params = match serde_json::from_value::(cur) { Ok(p) => p, - Err(e) => return Some(Err(format!("bad Camera Raw settings: {e}"))), + Err(e) => return Some(Err(format!("bad RAW Develop settings: {e}"))), }; if let Err(e) = next_params.validate_changes(&d.original) { - return Some(Err(format!("bad Camera Raw settings: {e}"))); + return Some(Err(format!("bad RAW Develop settings: {e}"))); } } let scope_update = match ui.get("scope") { diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs index dbae1e6ee7..12e168bd7b 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs @@ -16,9 +16,9 @@ pub(super) enum Target { /// A raw file opened interactively, shown in Camera Raw before it is kept (as Photoshop opens /// raws in Adobe Camera Raw first). The document is already developed with the defaults; Open /// re-develops it when Temperature, Tint, Exposure, Shadows, Highlights, Clarity, Texture, -/// Dehaze or the demosaic method changed (those act on the sensor data, see -/// [`photocraft_io::raw::import_raw_tuned`]) and applies the other settings as one Camera Raw -/// step, then marks the document unmodified. Cancel closes it. +/// Dehaze or the demosaic method changed, or the sidecar has a crop (those act on the sensor +/// data, see [`photocraft_io::raw::import_raw_tuned`]) and applies the other settings as one +/// Camera Raw step, then marks the document unmodified. Cancel closes it. #[derive(Clone, Debug)] pub struct RawOpen { pub document: photocraft_doc::DocId, @@ -30,6 +30,9 @@ pub struct RawOpen { pub developed_with: photocraft_io::raw::Demosaic, /// The method chosen in the dialog: Open re-develops when it differs from `developed_with`. pub demosaic: photocraft_io::raw::Demosaic, + /// The crop of the file's sidecar (in the raw's stored orientation): Open re-develops and + /// crops to it. The settings have no crop, so the dialog previews the whole frame. + pub crop: Option, } /// Should an interactive open of `name` show the open-time Camera Raw dialog? `warnings` are @@ -72,6 +75,8 @@ pub fn queue_open_dialog( bytes: bytes.map(|b| std::sync::Arc::new(b.to_vec())), developed_with: method, demosaic: method, + // Read now: a filmstrip raw that is never shown still opens with its sidecar's crop. + crop: path.and_then(read_sidecar).and_then(|(_, report, _)| report.crop), }; let held = super::filmstrip::HeldRaw::new(app, raw); app.raw_shelf.push(held); @@ -86,7 +91,7 @@ pub(super) fn open_raw(app: &mut PhotocraftApp, ctx: &egui::Context, raw: RawOpe /// [`open_raw`], or with `kept` settings and the settings they started from (a filmstrip raw /// shown again). -pub(super) fn open_raw_with(app: &mut PhotocraftApp, ctx: &egui::Context, raw: RawOpen, kept: Option<(CameraRaw, CameraRaw)>) -> Result<(), String> { +pub(super) fn open_raw_with(app: &mut PhotocraftApp, ctx: &egui::Context, mut raw: RawOpen, kept: Option<(CameraRaw, CameraRaw)>) -> Result<(), String> { let index = document_index(app, raw.document).ok_or("the raw document was closed")?; app.session.set_active(index); let (layer, surf, _) = crate::distort_ui::active_pixels(app)?; @@ -104,6 +109,7 @@ pub(super) fn open_raw_with(app: &mut PhotocraftApp, ctx: &egui::Context, raw: R let mut from_sidecar = false; if let Some((loaded, report, file)) = raw.path.as_deref().and_then(read_sidecar) { params = loaded; + raw.crop = report.crop; from_sidecar = true; app.ui.status = if report.ignored.is_empty() { crate::i18n::fmt(tl!("Settings from {name}"), &[("name", &file)]) @@ -208,6 +214,9 @@ pub(super) fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: clarity: params.clarity, texture: params.texture, dehaze: params.dehaze, + // The sidecar's crop: re-developing crops the document, before the Camera Raw step, so + // the post-crop vignette centres on the crop as in Camera Raw. + crop: raw.crop, }; // The open itself: the default settings, developed with the method it was opened with. let as_opened = photocraft_io::raw::RawTuning { demosaic: raw.developed_with, ..Default::default() }; @@ -387,9 +396,13 @@ pub fn opened_without_dialog(app: &mut PhotocraftApp, index: usize, name: &str, } let Some(document) = app.session.documents().get(index).map(|st| st.doc.id) else { return }; let method = photocraft_io::raw::developed_demosaic(warnings).unwrap_or_else(|| app.session.prefs().raw_defaults.demosaic.method()); - let raw = RawOpen { document, name: name.to_string(), path: path.map(str::to_string), bytes: None, developed_with: method, demosaic: method }; + let mut raw = + RawOpen { document, name: name.to_string(), path: path.map(str::to_string), bytes: None, developed_with: method, demosaic: method, crop: None }; let mut params = CameraRaw::default(); - let sidecar = path.and_then(read_sidecar).map(|(loaded, _, _)| loaded); + let sidecar = path.and_then(read_sidecar).map(|(loaded, report, _)| { + raw.crop = report.crop; + loaded + }); if let Some(loaded) = &sidecar { params = loaded.clone(); } else if app.session.prefs().raw_defaults.apply_auto_tone @@ -397,7 +410,7 @@ pub fn opened_without_dialog(app: &mut PhotocraftApp, index: usize, name: &str, { photocraft_algo::camera_raw::auto_tone(&px, &mut params); } - let r = if params.is_identity() { + let r = if params.is_identity() && raw.crop.is_none() { let defaults = app.session.prefs().raw_defaults.clone(); finish_open_raw(app, index, params, None, &raw, &defaults) } else { @@ -521,7 +534,7 @@ pub(super) enum Coverage { pub fn open(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { if photocraft_engine::color_channels::selected(&app.session).is_some_and(|c| c.len() > 1) { - return Err("Camera Raw requires the composite or one colour channel".into()); + return Err("RAW Develop requires the composite or one colour channel".into()); } photocraft_engine::commands::find("filter.cameraRaw").map(|c| (c.enabled)(&app.session)).unwrap_or(Err("unknown command".into()))?; let (layer, surf, _) = crate::distort_ui::active_pixels(app)?; @@ -539,7 +552,7 @@ pub fn open_smart_filter(app: &mut PhotocraftApp, ctx: &egui::Context, layer: La }; let filter = sm.smart_filters.get(index).ok_or("no such smart filter")?; if filter.command != RAW { - return Err("the smart filter is not a Camera Raw filter".into()); + return Err("the smart filter is not a RAW Develop filter".into()); } let params = raw_params(RAW, &filter.params).map_err(|e| e.to_string())?; let surf = photocraft_engine::smart_cmds::render_below_filter(&st.doc, sm, index) diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs index 9ac2f8c997..31b6d551d6 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/sidecar.rs @@ -88,7 +88,8 @@ pub(super) fn store_sidecar(app: &mut PhotocraftApp, raw: &RawOpen, params: &Cam None if params.is_identity() => return Stored::Defaults, _ => {} } - let bytes = photocraft_io::camera_raw_xmp::save(params).into_bytes(); + // The crop it opened with stays in the file, though the dialog has no control for it. + let bytes = photocraft_io::camera_raw_xmp::save_with_crop(params, raw.crop).into_bytes(); let Some(write) = app.services.write.as_mut() else { return Stored::Skipped }; if let Err(e) = write(&sidecar, &bytes) { crate::notices::error(app, crate::i18n::fmt(tl!("Could not write {name}: {error}"), &[("name", &name), ("error", &e)])); @@ -129,9 +130,9 @@ fn existing_sidecar_is_ours(_: &str) -> Option { /// Save Settings…: the dialog's settings as a Camera Raw `.xmp` settings file. pub(super) fn save_settings(app: &mut PhotocraftApp) -> Result { - let d = app.camera_raw.as_ref().ok_or(tl!("Camera Raw isn't open"))?; + let d = app.camera_raw.as_ref().ok_or(tl!("RAW Develop isn't open"))?; let bytes = photocraft_io::camera_raw_xmp::save(&d.params).into_bytes(); - app.pick_save("Camera Raw Settings.xmp", move |app, path| { + app.pick_save("RAW Develop Settings.xmp", move |app, path| { let write = app.services.write.as_mut().ok_or("no writer configured")?; write(&path, &bytes)?; Ok(json!({"path": path})) @@ -141,12 +142,17 @@ pub(super) fn save_settings(app: &mut PhotocraftApp) -> Result { /// Load Settings…: applies a Camera Raw `.xmp` settings file's supported settings over the /// dialog's; the status bar names how many were not supported. pub(super) fn load_settings(app: &mut PhotocraftApp) -> Result { - app.camera_raw.as_ref().ok_or(tl!("Camera Raw isn't open"))?; + app.camera_raw.as_ref().ok_or(tl!("RAW Develop isn't open"))?; app.pick_file_bytes_filtered(&["xmp"], |app, name, bytes| { let file = crate::file_open::display_name(&name); - let d = app.camera_raw.as_mut().ok_or(tl!("Camera Raw isn't open"))?; + let d = app.camera_raw.as_mut().ok_or(tl!("RAW Develop isn't open"))?; let mut next = d.params.clone(); - let report = photocraft_io::camera_raw_xmp::load(&mut next, &bytes).map_err(|e| format!("{file}: {e}"))?; + let mut report = photocraft_io::camera_raw_xmp::load(&mut next, &bytes).map_err(|e| format!("{file}: {e}"))?; + // A crop only applies as a raw file opens; the filter has none, so it is not supported. + if report.crop.take().is_some() { + report.applied = report.applied.saturating_sub(1); + report.ignored.extend(photocraft_io::camera_raw_xmp::CROP_KEYS.iter().take(4).map(|k| k.to_string())); + } next.validate_changes(&d.original).map_err(|e| format!("{file}: {e}"))?; if d.params.point_curve != next.point_curve { d.curve_state = Default::default(); @@ -158,9 +164,9 @@ pub(super) fn load_settings(app: &mut PhotocraftApp) -> Result { } app.ui.status_error = false; app.ui.status = if report.ignored.is_empty() { - crate::i18n::fmt(tl!("Loaded Camera Raw settings from {file}"), &[("file", &file)]) + crate::i18n::fmt(tl!("Loaded RAW Develop settings from {file}"), &[("file", &file)]) } else { - let template = "Loaded Camera Raw settings from {file} ({n} not supported)"; + let template = "Loaded RAW Develop settings from {file} ({n} not supported)"; crate::i18n::fmt(tl!(template), &[("file", &file), ("n", &report.ignored.len().to_string())]) }; Ok(json!({"applied": report.applied, "ignored": report.ignored})) diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs index 9c817414bc..eb8522ba50 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs @@ -111,7 +111,7 @@ fn finish_worker(d: &mut CameraRawDialog, ctx: &egui::Context) { } std::thread::sleep(std::time::Duration::from_millis(5)); } - panic!("the Camera Raw preview worker never finished"); + panic!("the RAW Develop preview worker never finished"); } /// The dialog's controls develop the proxy on a worker (#5964): the frame it shows is the one @@ -200,7 +200,7 @@ fn a_worker_failure_is_reported_until_the_next_frame() { }; let fail = |app: &mut PhotocraftApp| { let (tx, rx) = std::sync::mpsc::channel(); - tx.send(Err("Camera Raw preview failed".to_string())).unwrap(); + tx.send(Err("RAW Develop preview failed".to_string())).unwrap(); let d = app.camera_raw.as_mut().unwrap(); d.pending = Some(rx); d.dirty = false; @@ -213,7 +213,7 @@ fn a_worker_failure_is_reported_until_the_next_frame() { frame(&mut app); fail(&mut app); frame(&mut app); - assert!(app.ui.status_error && app.ui.status == "Camera Raw preview failed", "{}", app.ui.status); + assert!(app.ui.status_error && app.ui.status == "RAW Develop preview failed", "{}", app.ui.status); // No new frame yet: the error stays. frame(&mut app); assert!(app.ui.status_error); @@ -372,7 +372,7 @@ fn raw_opens_in_camera_raw_and_open_redevelops() { menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": 1.0, "temperature": 30, "contrast": 20}}})).unwrap().unwrap(); let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); assert_eq!(r["redeveloped"], true, "{r}"); - assert!(r.get("filter").is_some(), "contrast is applied as a Camera Raw step: {r}"); + assert!(r.get("filter").is_some(), "contrast is applied as a RAW Develop step: {r}"); assert!(app.camera_raw.is_none()); assert_eq!(app.session.documents().len(), 1); let st = app.session.active().unwrap(); @@ -705,7 +705,7 @@ fn auto_tone_of_a_never_shown_raw_matches_the_dialogs() { } } let method = photocraft_io::raw::Demosaic::Ahd; - let raw = RawOpen { document, name: "pattern.dng".into(), path: None, bytes: None, developed_with: method, demosaic: method }; + let raw = RawOpen { document, name: "pattern.dng".into(), path: None, bytes: None, developed_with: method, demosaic: method, crop: None }; let (unshown, _) = filmstrip::first_settings(&app, &raw); open_raw(&mut app, &ctx, raw).unwrap(); let shown = &app.camera_raw.as_ref().unwrap().params; @@ -729,7 +729,7 @@ fn cancel_closes_the_raw_and_the_preference_skips_the_dialog() { open_raw(&mut app, &ctx, raw).unwrap(); let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); assert_eq!((r["document"].as_u64(), r["redeveloped"].as_bool(), r.get("filter")), (Some(0), Some(false), None), "{r}"); - assert_eq!(r.get("defaults"), None, "ProPhoto, 16-bit: no Camera Raw Default to apply: {r}"); + assert_eq!(r.get("defaults"), None, "ProPhoto, 16-bit: no RAW Develop Default to apply: {r}"); // Preference off: raws open straight away. app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); app.open_bytes("c.dng", &dng).unwrap(); @@ -745,7 +745,8 @@ fn cancel_closes_the_raw_and_the_preference_skips_the_dialog() { path: None, bytes: None, developed_with: Default::default(), - demosaic: Default::default() + demosaic: Default::default(), + crop: None } ) .is_err() @@ -891,7 +892,7 @@ fn camera_raw_defaults_apply_when_a_raw_opens() { open_raw(&mut app, &ctx, raw).unwrap(); let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); assert_eq!(r["defaults"], json!(["sharpenFor", "colorSpace"]), "{r}"); - assert!(r.get("filter").is_some(), "Sharpen For is a Camera Raw step: {r}"); + assert!(r.get("filter").is_some(), "Sharpen For is a RAW Develop step: {r}"); let st = app.session.active().unwrap(); assert_eq!(st.doc.depth, photocraft_color::SampleType::U16); assert_eq!(st.saved_revision, st.revision); @@ -988,6 +989,74 @@ fn a_rating_only_sidecar_is_left_alone() { let _ = std::fs::remove_dir_all(&dir); } +/// #9985: the crop of a Lightroom sidecar crops the opened raw (with the dialog's Open and +/// without the dialog), and neither its edges nor the raw's file name are named as unsupported. +/// A straightened crop isn't applied and is named. PhotoCraft's own sidecar keeps the crop. +#[test] +fn a_sidecar_crop_crops_the_opened_raw() { + let lightroom = r#""#; + let (mut app, dng, dir, raw_path, written) = raw_with_sidecar("crop", Some(lightroom)); + let ctx = egui::Context::default(); + let size = |app: &PhotocraftApp| app.session.active().map(|st| (st.doc.size.width, st.doc.size.height)); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + assert!(app.ui.status.contains("IMG_0100.xmp") && !app.ui.status.contains("not supported"), "{}", app.ui.status); + assert_eq!(size(&app), Some((48, 32)), "the dialog previews the whole frame"); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(size(&app), Some((24, 16)), "Open crops the 48x32 frame to x 6..30, y 8..24"); + let st = app.session.active().unwrap(); + assert_eq!(st.saved_revision, st.revision, "the crop is part of opening: unmodified"); + assert!(written.lock().unwrap().is_empty(), "Lightroom's sidecar is kept"); + app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": false})).unwrap(); + app.open_file(&raw_path, &dng).unwrap(); + assert_eq!(size(&app), Some((24, 16)), "without the dialog too"); + app.run("prefs.set", json!({"path": "rawDefaults.openInCameraRaw", "value": true})).unwrap(); + // Straightened: the rectangle is measured on the turned frame, so nothing is cropped. + std::fs::write(sidecar_path(&raw_path), lightroom.replace(r#"crs:CropAngle="0""#, r#"crs:CropAngle="1.38""#)).unwrap(); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + assert!(app.ui.status.contains("CropAngle") && !app.ui.status.contains("RawFileName"), "{}", app.ui.status); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(size(&app), Some((48, 32))); + // PhotoCraft's own sidecar: a changed setting rewrites it, with the crop it was opened with. + let crop = photocraft_io::camera_raw_xmp::Crop { top: 0.25, left: 0.125, bottom: 0.75, right: 0.625 }; + std::fs::write(sidecar_path(&raw_path), photocraft_io::camera_raw_xmp::save_with_crop(&CameraRaw::default(), Some(crop))).unwrap(); + open_dialog_at(&mut app, &ctx, &dng, &raw_path); + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"contrast": 15}, "commit": true}})).unwrap().unwrap(); + assert_eq!(size(&app), Some((24, 16))); + let w = written.lock().unwrap().clone(); + assert_eq!(w.len(), 1); + let mut back = CameraRaw::default(); + let r = photocraft_io::camera_raw_xmp::load(&mut back, &w[0].1).unwrap(); + assert_eq!((back.contrast, r.crop), (15.0, Some(crop))); + let _ = std::fs::remove_dir_all(&dir); +} + +/// #9985 with the filmstrip: raws opened together each open with their own sidecar's crop, also +/// the one that is never shown and the one that was shown and left. +#[test] +fn filmstrip_raws_open_with_their_sidecar_crops() { + let lightroom = r#""#; + let (mut app, dng, dir, raw_path, _) = raw_with_sidecar("filmcrop", Some(lightroom)); + let paths: Vec = (1..3).map(|i| dir.join(format!("IMG_010{i}.cr2")).to_string_lossy().into_owned()).collect(); + for p in &paths { + std::fs::write(p, &dng).unwrap(); + std::fs::write(sidecar_path(p), lightroom).unwrap(); + } + let ctx = egui::Context::default(); + app.open_file(&raw_path, &dng).unwrap(); + for p in &paths { + app.open_file(p, &dng).unwrap(); + } + assert_eq!(app.raw_shelf.len(), 3); + filmstrip::open_held(&mut app, &ctx, 0).unwrap(); + filmstrip::show_raw(&mut app, &ctx, 1).unwrap(); + filmstrip::show_raw(&mut app, &ctx, 0).unwrap(); + let r = menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"commit": true}})).unwrap().unwrap(); + assert_eq!(r["opened"].as_array().map(Vec::len), Some(3), "{r}"); + let sizes: Vec<_> = app.session.documents().iter().map(|st| (st.doc.size.width, st.doc.size.height)).collect(); + assert_eq!(sizes, vec![(24, 16); 3], "shown, shown and left, and never shown: all cropped"); + let _ = std::fs::remove_dir_all(&dir); +} + /// With Open in Camera Raw off, opening a raw develops it with its sidecar and writes nothing /// back: nothing changed. #[test] diff --git a/crates/ui-egui/src/dialogs/color_picker_preview/tests.rs b/crates/ui-egui/src/dialogs/color_picker_preview/tests.rs index 4712394862..7901bbb387 100644 --- a/crates/ui-egui/src/dialogs/color_picker_preview/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker_preview/tests.rs @@ -209,7 +209,7 @@ fn damage_between_previews_is_the_text_layer_only() { // The canvas asks through `damage_since`, with the display's key folded into what it cached. let doc = app.session.active().unwrap().doc.clone(); let dk = crate::canvas::canvas_display(&app, &doc, None).1; - let since = |seen: u64, now: u64| crate::canvas::damage_since(&app, 0, (revision, seen ^ dk), (revision, now), dk, None); + let since = |seen: u64, now: u64| crate::canvas::damage_since(&app, 0, (revision, seen ^ dk), (revision, now), dk, (revision, None)); assert_eq!(since(red, blue), Some(bounds), "the canvas refreshes only the text layer between colours"); assert_eq!(since(blue, 0), Some(bounds), "and on Cancel"); } @@ -260,7 +260,7 @@ fn ok_counts_the_previewed_canvas_as_the_document_so_only_the_layer_is_redrawn() assert_eq!(seen.1, dk, "gradient={gradient}: OK's edit is what the canvas already shows"); // So the commit's own damage is all the canvas refreshes, not the whole document. let edit = photocraft_geom::Rect::new(1, 2, 3, 4); - let damage = crate::canvas::damage_since(&app, 0, seen, (revision, 0), dk, Some(edit)); + let damage = crate::canvas::damage_since(&app, 0, seen, (revision, 0), dk, (revision - 1, Some(edit))); assert_eq!(damage, Some(edit), "gradient={gradient}"); } } diff --git a/crates/ui-egui/src/dialogs/color_picker_ui.rs b/crates/ui-egui/src/dialogs/color_picker_ui.rs index d59bf082c3..1c76f566fa 100644 --- a/crates/ui-egui/src/dialogs/color_picker_ui.rs +++ b/crates/ui-egui/src/dialogs/color_picker_ui.rs @@ -271,6 +271,10 @@ fn set_field(f: &mut Map, field: &str, value: Value) -> Result<() /// Opens the Color Picker dialog `id`'s body asked for ([`request`], [`request_field`]), on its /// colour: OK sets that field of the dialog (not the foreground), Cancel leaves it as it was. +/// +/// A dialog can provide `__pickColorDefault` when its field is a non-colour choice that has not +/// yet been replaced by the picked colour. The temporary default seeds the picker without +/// changing the parent field; it is removed before the picker opens. pub fn open_requested(app: &mut PhotocraftApp, id: u64) { let Some(d) = app.ui.dialog_mut(id) else { return }; let (title, field) = match d.fields.remove(REQUEST) { @@ -282,7 +286,11 @@ pub fn open_requested(app: &mut PhotocraftApp, id: u64) { } _ => return, }; - let rgb = field_value(&d.fields, &field).and_then(parse_hex).unwrap_or([0.0; 3]); + let rgb = field_value(&d.fields, &field) + .and_then(parse_hex) + .or_else(|| d.fields.get("__pickColorDefault").and_then(Value::as_str).and_then(parse_hex)) + .unwrap_or([0.0; 3]); + d.fields.remove("__pickColorDefault"); open_for_field(app, &title, rgb, id, &field); } diff --git a/crates/ui-egui/src/dialogs/discard_ui.rs b/crates/ui-egui/src/dialogs/discard_ui.rs index b08fb22247..9871bf0865 100644 --- a/crates/ui-egui/src/dialogs/discard_ui.rs +++ b/crates/ui-egui/src/dialogs/discard_ui.rs @@ -23,6 +23,12 @@ pub struct Prompt { docs: Vec, /// The document whose question has already put keyboard focus on its default answer. focused: Option, + /// "Apply to All" is ticked. It is only offered while more than one document is left to ask about. + apply_all: bool, + /// The answer given to every document still to ask about, once "Apply to All" was used. + auto: Option, + /// The document `auto` answered last: if it is asked about again, its save didn't go through. + auto_answered: Option, } fn index_of(app: &PhotocraftApp, id: DocId) -> Option { @@ -79,7 +85,7 @@ pub fn intercept(app: &mut PhotocraftApp, id: &str, params: &Value) -> bool { log::warn!("quitting a window that lost its GPU device before its unsaved work could be saved for recovery"); return false; } - let prompt = Prompt { id: id.to_string(), params: params.clone(), target, docs, focused: None }; + let prompt = Prompt { id: id.to_string(), params: params.clone(), target, docs, focused: None, apply_all: false, auto: None, auto_answered: None }; match &app.discard { None => ask(app, prompt), // Quitting overrides whatever is pending: it covers every document, so nothing is lost. @@ -180,6 +186,8 @@ fn advance(app: &mut PhotocraftApp, ctx: &egui::Context) { show_tab(app, rest.first().copied()); if let Some(p) = app.discard.as_mut() { p.docs = rest; + // Apply to All covered the documents asked about; these are asked about afresh. + (p.apply_all, p.auto, p.auto_answered) = (false, None, None); } return; } @@ -269,11 +277,32 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let Some(p) = &app.discard else { return }; let Some(&doc) = p.docs.first() else { return }; let (exits, reverts) = (p.id == EXIT, p.id == "file.revert"); + let (focus, offer_all) = (p.focused != Some(doc), p.docs.len() > 1 && !reverts); let Some(name) = index_of(app, doc).map(|i| app.session.documents()[i].doc.name.clone()) else { // Closed by something else while the prompt was up: nothing left to ask about. advance(app, ctx); return; }; + // "Apply to All" answers the rest one document per frame, as Photoshop does. A document that + // comes back (its save was cancelled or failed) is asked about normally again, so a save that + // can't succeed never repeats on its own. + match app.discard.as_ref().and_then(|p| p.auto.map(|a| (a, p.auto_answered == Some(doc)))) { + Some((answer, false)) => { + if let Some(p) = app.discard.as_mut() { + p.auto_answered = Some(doc); + } + apply(app, ctx, doc, answer); + ctx.request_repaint(); + return; + } + Some((_, true)) => { + if let Some(p) = app.discard.as_mut() { + p.auto = None; + p.apply_all = false; + } + } + None => {} + } let (title, message) = if reverts { ("Revert", crate::i18n::fmt(tl!("Revert “{name}” to the last saved version? Your changes will be lost."), &[("name", &name)])) } else { @@ -286,7 +315,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { }; // Each question comes up with its default answer focused, as in Photoshop: the arrow keys then // move between the answers and Enter presses the focused one (#6441). - let focus = p.focused != Some(doc); + let mut apply_all = app.discard.as_ref().is_some_and(|p| p.apply_all); if let Some(p) = app.discard.as_mut() { p.focused = Some(doc); } @@ -319,6 +348,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::widgets::hairline(ui); ui.add_space(8.0); ui.label(message); + ui.add_space(8.0); + if offer_all { + crate::widgets::checkbox(ui, &mut apply_all, tl!("Apply to All")); + } ui.add_space(12.0); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.spacing_mut().item_spacing.x = 10.0; @@ -334,11 +367,28 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { if answer.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Enter)) { answer = buttons.iter().find(|b| b.0 == ButtonRole::Default).map(|b| b.4); } + if let Some(p) = app.discard.as_mut() { + p.apply_all = apply_all; + } if let Some(answer) = answer { + if apply_all && offer_all { + apply_to_rest(app, doc, answer); + } apply(app, ctx, doc, answer); } } +/// Makes a Save or Don't Save answer about `doc` the answer for every document still to ask about. +fn apply_to_rest(app: &mut PhotocraftApp, doc: DocId, answer: Answer) { + if !matches!(answer, Answer::Save | Answer::Discard) { + return; + } + if let Some(p) = app.discard.as_mut() { + p.auto = Some(answer); + p.auto_answered = Some(doc); + } +} + /// Acts on the answer about `doc`, the document the prompt is asking about. fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId, answer: Answer) { match answer { @@ -360,7 +410,8 @@ pub fn inspect(app: &PhotocraftApp) -> Option { let doc = *p.docs.first()?; let name = index_of(app, doc).and_then(|i| app.session.documents().get(i)).map(|d| d.doc.name.clone())?; let reverts = p.id == "file.revert"; - let (choices, default): (&[&str], _) = if reverts { (&["dontSave", "cancel"], "dontSave") } else { (&["save", "dontSave", "cancel"], "save") }; + let choices = choices(reverts, p.docs.len() > 1); + let default = if reverts { "dontSave" } else { "save" }; Some(json!({ "id": CONTROL_ID, "kind": "unsavedChanges", @@ -375,8 +426,19 @@ pub fn pending_command(app: &PhotocraftApp) -> Option<(String, Value)> { app.discard.as_ref().map(|p| (p.id.clone(), p.params.clone())) } +/// The answers a control client can give: `save`, `dontSave` and `cancel`, plus `saveAll` and +/// `dontSaveAll` (the "Apply to All" box) while more than one document is left to ask about. +/// Revert takes `dontSave` or `cancel` only. +fn choices(reverts: bool, several: bool) -> Vec<&'static str> { + match (reverts, several) { + (true, _) => vec!["dontSave", "cancel"], + (false, false) => vec!["save", "dontSave", "cancel"], + (false, true) => vec!["save", "saveAll", "dontSave", "dontSaveAll", "cancel"], + } +} + /// Answers the prompt for a control client: `save`, `dontSave` or `cancel` (Revert takes -/// `dontSave` or `cancel`). Like the buttons, Save may first ask for a path in the save dialog. +/// `dontSave` or `cancel`); `saveAll` and `dontSaveAll` answer for every document still to ask about. Like the buttons, Save may first ask for a path in the save dialog. pub fn answer_control(app: &mut PhotocraftApp, ctx: &egui::Context, choice: &str) -> Result { let Some(doc) = app.discard.as_ref().and_then(|p| p.docs.first().copied()) else { return Err("no unsaved-changes prompt is open".into()); @@ -385,15 +447,26 @@ pub fn answer_control(app: &mut PhotocraftApp, ctx: &egui::Context, choice: &str return Err("the unsaved-changes prompt is waiting for a save to finish".into()); } let reverts = app.discard.as_ref().is_some_and(|p| p.id == "file.revert"); - let answer = match choice { - "save" if !reverts => Answer::Save, - "dontSave" => Answer::Discard, - "cancel" => Answer::Cancel, + let several = app.discard.as_ref().is_some_and(|p| p.docs.len() > 1); + let (answer, all) = match choice { + "save" if !reverts => (Answer::Save, false), + "saveAll" if !reverts && several => (Answer::Save, true), + "dontSave" => (Answer::Discard, false), + "dontSaveAll" if !reverts && several => (Answer::Discard, true), + "cancel" => (Answer::Cancel, false), other => { - let choices = if reverts { "dontSave or cancel" } else { "save, dontSave or cancel" }; - return Err(format!("unknown choice `{other}`: {choices}")); + let choices = choices(reverts, several); + let (last, rest) = choices.split_last().unwrap_or((&"cancel", &[])); + return Err(format!("unknown choice `{other}`: {} or {last}", rest.join(", "))); } }; + // The client's answer replaces one Apply to All left behind (a save that failed at once). + if let Some(p) = app.discard.as_mut() { + (p.apply_all, p.auto, p.auto_answered) = (false, None, None); + } + if all { + apply_to_rest(app, doc, answer); + } apply(app, ctx, doc, answer); Ok(json!({"open": app.discard.is_some(), "fileDialog": app.file_dialog_open()})) } diff --git a/crates/ui-egui/src/dialogs/discard_ui/tests.rs b/crates/ui-egui/src/dialogs/discard_ui/tests.rs index 5617e0245a..c92cc666d7 100644 --- a/crates/ui-egui/src/dialogs/discard_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/discard_ui/tests.rs @@ -235,17 +235,24 @@ fn drawn_order<'a>(h: &Prompted, labels: [&'a str; 3]) -> Vec<&'a str> { } /// Tab walks `labels` left to right from the focused default answer, `labels[default]`, and -/// wraps; Shift+Tab steps back. +/// wraps; Shift+Tab steps back. When the prompt offers "Apply to All", that box is one more +/// stop, in front of the answers. fn tab_walks(h: &mut Prompted, labels: [&str; 3], default: usize) { - assert_eq!(focused(h, &labels), Some(labels[default])); - for step in 1..=3 { + use egui_kittest::kittest::Queryable; + let mut stops = labels.to_vec(); + if h.query_by_label("Apply to All").is_some() { + stops.insert(0, "Apply to All"); + } + let (n, at) = (stops.len(), default + stops.len() - 3); + assert_eq!(focused(h, &stops), Some(stops[at])); + for step in 1..=n { h.key_press(Key::Tab); h.run_steps(2); - assert_eq!(focused(h, &labels), Some(labels[(default + step) % 3])); + assert_eq!(focused(h, &stops), Some(stops[(at + step) % n])); } h.key_press_modifiers(egui::Modifiers::SHIFT, Key::Tab); h.run_steps(2); - assert_eq!(focused(h, &labels), Some(labels[(default + 2) % 3])); + assert_eq!(focused(h, &stops), Some(stops[(at + n - 1) % n])); } fn docs_left(h: &Prompted) -> Option { @@ -298,6 +305,111 @@ fn windows_and_linux_ask_yes_no_cancel_with_the_default_first() { } } +/// "Apply to All" (a checkbox, as in Photoshop) gives the answer to every document still to ask about. +#[test] +fn apply_to_all_discards_the_rest_without_asking_again() { + use egui_kittest::kittest::Queryable; + let mut h = prompt_on(egui::os::OperatingSystem::Windows); + h.get_by_label("Apply to All").click(); + h.run_steps(2); + h.key_press(Key::N); + h.run_steps(8); + assert!(h.state().discard.is_none()); + assert!(h.state().session.documents().is_empty(), "No was applied to both unsaved documents"); +} + +#[test] +fn apply_to_all_is_only_offered_while_several_documents_are_left() { + use egui_kittest::kittest::Queryable; + let mut one_dirty = app_with_docs(2); + make_dirty(&mut one_dirty, 0); + let h = prompt_for(one_dirty, "file.closeAll", egui::os::OperatingSystem::Windows); + assert!(h.query_by_label("Apply to All").is_none(), "only one document is unsaved"); + let h = prompt_on(egui::os::OperatingSystem::Windows); + assert!(h.query_by_label("Apply to All").is_some()); +} + +/// A save that was cancelled or failed brings its document back: asking again beats retrying forever. +#[test] +fn a_document_that_comes_back_after_apply_to_all_is_asked_about_again() { + let mut h = prompt_on(egui::os::OperatingSystem::Windows); + let first = doc_id(h.state(), 0); + if let Some(p) = h.state_mut().discard.as_mut() { + (p.apply_all, p.auto, p.auto_answered) = (true, Some(Answer::Save), Some(first)); + } + h.run_steps(3); + let prompt = h.state().discard.as_ref().unwrap(); + assert!(prompt.auto.is_none() && !prompt.apply_all); + assert_eq!(docs_left(&h), Some(2), "both documents are still waiting for an answer"); +} + +/// Apply to All answers for the documents the prompt opened with, not for ones dirtied since. +#[test] +fn a_document_dirtied_after_apply_to_all_is_asked_about() { + let mut app = app_with_docs(3); + make_dirty(&mut app, 0); + make_dirty(&mut app, 1); + let mut h = prompt_for(app, "file.closeAll", egui::os::OperatingSystem::Windows); + let late = doc_id(h.state(), 2); + make_dirty(h.state_mut(), 2); + if let Some(p) = h.state_mut().discard.as_mut() { + (p.apply_all, p.auto) = (true, Some(Answer::Discard)); + } + h.run_steps(8); + let prompt = h.state().discard.as_ref().unwrap(); + assert_eq!(prompt.docs, vec![late], "the two unsaved documents were discarded, the late one is asked about"); + assert!(prompt.auto.is_none() && !prompt.apply_all); + assert_eq!(h.state().session.documents().len(), 1); +} + +#[test] +fn control_clients_can_answer_for_all() { + let mut app = app_with_docs(3); + for i in 0..3 { + make_dirty(&mut app, i); + } + let mut h = prompt_for(app, "file.closeAll", egui::os::OperatingSystem::Windows); + let choices = inspect(h.state()).unwrap()["fields"]["choices"].clone(); + assert_eq!(choices, json!(["save", "saveAll", "dontSave", "dontSaveAll", "cancel"])); + let ctx = h.ctx.clone(); + answer_control(h.state_mut(), &ctx, "dontSaveAll").unwrap(); + h.run_steps(8); + assert!(h.state().discard.is_none()); + assert!(h.state().session.documents().is_empty()); +} + +/// A client answering one document isn't overruled by an Apply to All whose save just failed. +#[test] +fn a_control_answer_clears_a_stale_apply_to_all() { + let mut app = app_with_docs(3); + for i in 0..3 { + make_dirty(&mut app, i); + } + let mut h = prompt_for(app, "file.closeAll", egui::os::OperatingSystem::Windows); + let (first, last) = (doc_id(h.state(), 0), doc_id(h.state(), 2)); + if let Some(p) = h.state_mut().discard.as_mut() { + (p.apply_all, p.auto, p.auto_answered) = (true, Some(Answer::Discard), Some(first)); + } + let ctx = h.ctx.clone(); + answer_control(h.state_mut(), &ctx, "dontSave").unwrap(); + h.run_steps(8); + let prompt = h.state().discard.as_ref().unwrap(); + assert_eq!(prompt.docs.len(), 2, "only the answered document was closed"); + assert!(prompt.docs.contains(&last) && prompt.auto.is_none()); +} + +#[test] +fn the_all_answers_need_more_than_one_document_left() { + let mut app = app_with_docs(1); + make_dirty(&mut app, 0); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "file.close", json!({})).unwrap(); + assert_eq!(inspect(&app).unwrap()["fields"]["choices"], json!(["save", "dontSave", "cancel"])); + let err = answer_control(&mut app, &ctx, "saveAll").unwrap_err(); + assert!(err.contains("unknown choice `saveAll`") && err.ends_with("save, dontSave or cancel"), "{err}"); + assert!(app.discard.is_some(), "a refused answer leaves the prompt up"); +} + /// Whether the prompt is asking about the document called `name`. fn asks_about(h: &Prompted, name: &str) -> bool { use egui_kittest::kittest::Queryable; diff --git a/crates/ui-egui/src/dialogs/dont_show_again.rs b/crates/ui-egui/src/dialogs/dont_show_again.rs new file mode 100644 index 0000000000..da21ce4087 --- /dev/null +++ b/crates/ui-egui/src/dialogs/dont_show_again.rs @@ -0,0 +1,57 @@ +//! An alert (text plus OK) with a "Don't show again" box, as the reference shows for warnings such +//! as the Content-Aware Move tool's "No pixels are selected." (#12192). The box's choice is kept +//! with the other dialog preferences under the key the alert was opened with, and the alert is not +//! opened again once it was ticked. + +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::state::{Dialog, DialogKind}; + +/// Marks the alert; its value is the dialog preference ([`photocraft_engine::prefs::Preferences::dialogs`]) +/// the box sets. +const PREF: &str = "__dontShowAgain"; + +/// Whether "Don't show again" was ticked on the alert remembered as `pref`. +pub fn dismissed(app: &PhotocraftApp, pref: &str) -> bool { + app.session.prefs().dialogs.get(pref).and_then(|v| v.get("skip")).and_then(Value::as_bool) == Some(true) +} + +/// Show `message` with OK and "Don't show again": not once that was ticked, and not a second one +/// while it is already open. +pub fn alert(app: &mut PhotocraftApp, message: &str, pref: &str) { + if dismissed(app, pref) || app.ui.dialogs.iter().any(|d| d.kind == DialogKind::Error && d.fields.get(PREF).and_then(Value::as_str) == Some(pref)) { + return; + } + let mut fields = Map::new(); + fields.insert("message".into(), json!(message)); + fields.insert(PREF.into(), json!(pref)); + fields.insert("skip".into(), json!(false)); + app.ui.open_dialog(DialogKind::Error, fields); +} + +/// The box under an alert's text, on alerts opened by [`alert`]. +pub fn body(ui: &mut egui::Ui, fields: &mut Map) { + if !fields.contains_key(PREF) { + return; + } + ui.add_space(8.0); + let mut skip = fields.get("skip").and_then(Value::as_bool).unwrap_or(false); + ui.checkbox(&mut skip, tl!("Don't show again")); + fields.insert("skip".into(), json!(skip)); +} + +/// The alert `d` closed (OK, Esc or its close box): keep a ticked "Don't show again". +pub fn closed(app: &mut PhotocraftApp, d: &Dialog) { + let Some(pref) = d.fields.get(PREF).and_then(Value::as_str).filter(|_| d.kind == DialogKind::Error) else { return }; + if d.fields.get("skip").and_then(Value::as_bool) != Some(true) { + return; + } + app.session.edit_prefs(|prefs| { + prefs.dialogs.insert(pref.into(), json!({"skip": true})); + }); + if let Err(error) = crate::prefs_ui::save_preferences(app) { + app.ui.status = crate::i18n::fmt(tl!("The preference could not be saved: {error}"), &[("error", &error)]); + app.ui.status_error = true; + } +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 5923fb4d2d..2464721efd 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -6,6 +6,8 @@ use std::sync::Arc; +use photocraft_cms::{ColorSpace, TransformOptions}; +use photocraft_color::ColorMode; use photocraft_doc::Document; use photocraft_engine::color_cmds::ColorSettings; use photocraft_engine::installed_profiles::InstalledProfile; @@ -431,6 +433,9 @@ fn default_value(app: &PhotocraftApp, command: &str, p: &Param) -> Option /// Command-specific open defaults (ruler straighten, warp from layer, …), not remembered prefs. fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map) { + if command == "image.mode.indexedColor" { + indexed_matte_defaults(app, fields); + } if command == "image.rotation.arbitrary" { straighten_defaults(app, fields); } @@ -859,6 +864,109 @@ fn replace_color_result(ui: &mut egui::Ui, f: &mut Map) { } } +const INDEXED_MATTE_FOREGROUND: &str = "__indexedMatteForeground"; +const INDEXED_MATTE_BACKGROUND: &str = "__indexedMatteBackground"; +const INDEXED_MATTE_COLOR_ERROR: &str = "__indexedMatteColorError"; + +/// Resolve a tool colour into the encoded samples used by Indexed Color's matte. +/// +/// The picker and command fields carry document RGB coordinates. Tool swatches are +/// working-RGB coordinates, so only the named tool choices need this conversion here. +fn indexed_matte_document_color(app: &PhotocraftApp, doc: &Document, color: [f32; 4]) -> Result<[f32; 3], String> { + let destination = match photocraft_engine::color_cmds::mode_space(doc.mode) { + ColorSpace::Rgb | ColorSpace::Gray => photocraft_engine::color_cmds::document_profile(doc), + _ => photocraft_engine::color_cmds::composite_profile(doc), + }; + let source = app.session.color.working(ColorMode::Rgb); + let options = TransformOptions { intent: app.session.color.settings.intent(), bpc: app.session.color.settings.bpc, ..Default::default() }; + let transform = photocraft_cms::transform::cached(&source, &destination, options).map_err(|e| e.to_string())?; + let mut output = [0.0; 16]; + transform.eval(&color[..3], &mut output); + let rgb = if destination.color_space == ColorSpace::Gray { [output[0]; 3] } else { [output[0], output[1], output[2]] }; + if rgb.iter().any(|v| !v.is_finite()) { + return Err("cannot convert matte colour to finite document samples".into()); + } + Ok(rgb.map(|v| v.clamp(0.0, 1.0))) +} + +fn indexed_matte_defaults(app: &PhotocraftApp, fields: &mut Map) { + let Some(doc) = app.session.active().map(|state| state.doc.as_ref()) else { return }; + for (key, color) in [(INDEXED_MATTE_FOREGROUND, app.session.tools.foreground), (INDEXED_MATTE_BACKGROUND, app.session.tools.background)] { + match indexed_matte_document_color(app, doc, color) { + Ok(rgb) => { + fields.insert(key.into(), json!(crate::color_picker_ui::hex(rgb))); + } + Err(error) => { + fields.insert(INDEXED_MATTE_COLOR_ERROR.into(), json!(error)); + } + } + } +} + +fn indexed_matte_seed(fields: &Map, value: &str) -> Option<[f32; 3]> { + match value { + "foreground" => fields.get(INDEXED_MATTE_FOREGROUND).and_then(Value::as_str).and_then(crate::color_picker_ui::parse_hex), + "background" => fields.get(INDEXED_MATTE_BACKGROUND).and_then(Value::as_str).and_then(crate::color_picker_ui::parse_hex), + "black" => Some([0.0; 3]), + "gray" => Some([128.0 / 255.0; 3]), + "netscapeGray" => Some([192.0 / 255.0; 3]), + "none" | "white" => Some([1.0; 3]), + _ => crate::color_picker_ui::parse_hex(value), + } +} + +fn indexed_matte_row(ui: &mut egui::Ui, fields: &mut Map) { + let value = fields.get("matte").and_then(Value::as_str).unwrap_or("none"); + let mut choice = if value.starts_with('#') { "custom" } else { value }; + let color = indexed_matte_seed(fields, value); + let mut changed = false; + let mut pick = false; + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Matte")).color(Tokens::get(ui.ctx()).text_dim)); + changed = crate::widgets::dropdown( + ui, + "indexed-matte", + "Matte", + &mut choice, + &[ + ("none", "None"), + ("foreground", "Foreground Color"), + ("background", "Background Color"), + ("white", "White"), + ("black", "Black"), + ("gray", "50% Gray"), + ("netscapeGray", tl!("Netscape Gray")), + ("custom", "Other…"), + ], + 170.0, + ); + if choice == "custom" + && let Some(color) = color + { + let bytes = color.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + pick = crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(bytes[0], bytes[1], bytes[2]), tl!("Matte")).clicked(); + } + }); + if color.is_none() + && let Some(error) = fields.get(INDEXED_MATTE_COLOR_ERROR).and_then(Value::as_str) + { + ui.colored_label(Tokens::get(ui.ctx()).danger, error); + } + let custom = choice == "custom"; + if changed { + if custom && let Some(color) = color { + // Keep the previous matte until the picker confirms; the picker uses this only as + // its initial document-encoded colour when switching from a named matte or None. + fields.insert("__pickColorDefault".into(), json!(crate::color_picker_ui::hex(color))); + } else if !custom { + fields.insert("matte".into(), json!(choice.to_owned())); + } + } + if custom && color.is_some() && (changed || pick) { + crate::color_picker_ui::request_field(fields, "matte", &crate::color_picker_ui::title_for("Matte")); + } +} + /// Dialog body for filter commands. pub fn body(ui: &mut egui::Ui, f: &mut Map) { let t = Tokens::get(ui.ctx()); @@ -875,6 +983,10 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { crate::select_mask_view::controls(ui, f); } for p in parse_spec(&spec) { + if cmd == "image.mode.indexedColor" && p.key == "matte" { + indexed_matte_row(ui, f); + continue; + } if zoom_center::owns(&cmd, f) && matches!(p.key.as_str(), "centerX" | "centerY") { if p.key == "centerX" { zoom_center::row(ui, f); @@ -1193,6 +1305,7 @@ pub fn preview_document_with( photocraft_engine::channel_cmds::ChannelTarget::Composite, &[], &ColorSettings::default(), + None, ) } @@ -1200,6 +1313,8 @@ pub fn preview_document_with( /// `documents` are the open documents in session order: document params (Match Color's Source, /// Displace's map) index into them. `color` is the app's Edit › Color Settings: Assign and Convert /// to Profile's `working` is the working space chosen there, not the built-in default. +/// `tool_colors` carries the caller's working-space foreground/background values; standalone +/// previews without a session use the engine's default tool colors. #[allow(clippy::too_many_arguments)] pub(crate) fn preview_document_for_target( doc: &Document, @@ -1211,6 +1326,7 @@ pub(crate) fn preview_document_for_target( target: photocraft_engine::channel_cmds::ChannelTarget, documents: &[Arc], color: &ColorSettings, + tool_colors: Option<([f32; 4], [f32; 4])>, ) -> Option { if command == crate::select_mask_view::COMMAND { return crate::select_mask_view::preview_document(doc, active, params, k, cancel); @@ -1246,6 +1362,10 @@ pub(crate) fn preview_document_for_target( } let mut s = photocraft_engine::Session::new(); s.color.settings = color.clone(); + if let Some((foreground, background)) = tool_colors { + s.tools.foreground = foreground; + s.tools.background = background; + } s.set_inline_job_ctx(cancel.cloned()); let doc_id = proxy.id; s.add_document(proxy, None); @@ -1388,11 +1508,12 @@ pub struct FilterPreviewKey { pub command: String, pub params: Value, pub k: u32, + pub tool_colors: ([f32; 4], [f32; 4]), } impl FilterPreviewKey { /// Everything except the parameters: same dialog, document, revision, layer, channel target, - /// command and proxy factor. + /// command, proxy factor and tool colors. /// /// The canvas shows whatever this preview was computed for, so a result whose parameters are /// a few frames old still belongs on screen while a slider is moving; matching on everything @@ -1414,6 +1535,7 @@ impl FilterPreviewKey { && self.active == other.active && self.target == other.target && self.command == other.command + && self.tool_colors == other.tool_colors } } diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index de9f389e23..74e3f806eb 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -90,6 +90,34 @@ fn display_names_are_not_split_like_camel_case_keys() { assert_eq!(source_label("centerX"), "Center X"); } +#[test] +fn indexed_matte_tool_seeds_use_document_encoded_rgb() { + use photocraft_cms::Transform; + + let mut session = photocraft_engine::Session::new(); + session.color.settings.working_rgb = "display-p3".into(); + session.execute("file.new", json!({"width": 2, "height": 2, "background": "transparent"})).unwrap(); + session.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + session.execute("tools.setColors", json!({"foreground": "#3366cc", "background": "#cc6633"})).unwrap(); + let app = PhotocraftApp::new(session, crate::Services::default()); + let mut fields = Map::new(); + indexed_matte_defaults(&app, &mut fields); + + let doc = app.session.active().unwrap().doc.clone(); + let source = app.session.color.working(ColorMode::Rgb); + let destination = photocraft_engine::color_cmds::document_profile(&doc); + let transform = Transform::new(&source, &destination, app.session.color.settings.intent(), app.session.color.settings.bpc).unwrap(); + for (key, input) in [(INDEXED_MATTE_FOREGROUND, [0.2, 0.4, 0.8]), (INDEXED_MATTE_BACKGROUND, [0.8, 0.4, 0.2])] { + let mut output = [0.0; 16]; + transform.eval(&input, &mut output); + let expected = crate::color_picker_ui::hex([output[0], output[1], output[2]]); + assert_eq!(fields.get(key).and_then(Value::as_str), Some(expected.as_str()), "{key}"); + assert_eq!( + indexed_matte_seed(&fields, if key == INDEXED_MATTE_FOREGROUND { "foreground" } else { "background" }), + crate::color_picker_ui::parse_hex(&expected) + ); + } +} /// Convert to Profile's and Proof Setup's `bpc` read "Bpc": spelled out. #[test] fn black_point_compensation_is_spelled_out() { @@ -106,6 +134,7 @@ fn key() -> FilterPreviewKey { command: "filter.blur.gaussianBlur".into(), params: json!({"radius": 4.0}), k: 1, + tool_colors: ([0.0, 0.0, 0.0, 1.0], [1.0; 4]), } } @@ -128,6 +157,8 @@ fn same_target_ignores_parameters_but_nothing_else() { |k: &mut FilterPreviewKey| k.target = photocraft_engine::channel_cmds::ChannelTarget::LayerMask, |k: &mut FilterPreviewKey| k.command = "filter.blur.motionBlur".into(), |k: &mut FilterPreviewKey| k.k = 2, + |k: &mut FilterPreviewKey| k.tool_colors.0 = [0.2, 0.4, 0.8, 1.0], + |k: &mut FilterPreviewKey| k.tool_colors.1 = [0.8, 0.4, 0.2, 1.0], ] { let mut other = base.clone(); break_it(&mut other); @@ -653,6 +684,7 @@ fn smart_displace_preview_uses_the_map_document() { photocraft_engine::channel_cmds::ChannelTarget::Composite, &documents, &ColorSettings::default(), + None, ) .unwrap_or_else(|| panic!("map {map}: no preview")); assert!(photocraft_compose::render(&preview, doc.bounds()).px == want, "map {map}: the preview differs from what OK applies"); @@ -695,6 +727,7 @@ fn match_color_preview_uses_the_source_document() { photocraft_engine::channel_cmds::ChannelTarget::Composite, &documents, &ColorSettings::default(), + None, ) .unwrap_or_else(|| panic!("{label}: no preview")); let got = preview.layers[0].surface().unwrap().pixel(24, 16); @@ -711,6 +744,7 @@ fn match_color_preview_uses_the_source_document() { photocraft_engine::channel_cmds::ChannelTarget::Composite, &documents, &ColorSettings::default(), + None, ) .unwrap(); let px = preview.layers[0].surface().unwrap().pixel(12, 8); @@ -1716,3 +1750,80 @@ fn replace_color_localized_color_clusters() { assert!(px(2)[1] > 0.5, "near the point: shifted to green {:?}", px(2)); assert!(px(38)[0] > 0.9 && px(38)[1] < 0.1, "far away: still red {:?}", px(38)); } + +#[test] +fn indexed_matte_dropdown_and_picker_change_the_applied_edge_color() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + + for (choice, matte) in [("Black", [0.0, 0.0, 0.0]), ("50% Gray", [128.0 / 255.0; 3]), ("Netscape Gray", [192.0 / 255.0; 3]), ("Other…", [0.0, 0.0, 1.0])] + { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 2, "height": 1, "depth": 32, "background": "transparent"})).unwrap(); + session + .edit("fixture", |doc, active| { + let bounds = doc.bounds(); + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().write_region(bounds, &[1.0, 0.0, 0.0, 0.75, 0.0, 0.0, 0.0, 0.0]); + Ok(()) + }) + .unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(900.0, 1000.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(harness.state_mut(), "image.mode.indexedColor").unwrap(); + harness.state_mut().ui.dialog_mut(id).unwrap().fields.insert("palette".into(), json!("exact")); + harness.run_steps(3); + harness.query_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).expect("Matte dropdown").click(); + harness.run_steps(2); + harness.get_by_label(choice).click(); + harness.run_steps(3); + if choice == "Other…" { + let picker = harness.state().ui.dialogs.last().unwrap().id; + assert_ne!(picker, id); + harness.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), json!("#0000ff")); + crate::dialogs::confirm(harness.state_mut(), picker).unwrap(); + harness.state_mut().ui.dialogs.retain(|dialog| dialog.id != picker); + harness.run_steps(3); + } + harness.get_by_label("OK").click(); + harness.run_steps(3); + let doc = &harness.state().session.active().unwrap().doc; + assert_eq!(doc.mode, photocraft_color::ColorMode::Indexed); + let surface = doc.layers[0].surface().unwrap(); + let edge = surface.rgba(0, 0); + let expected = [0.75 + 0.25 * matte[0], 0.25 * matte[1], 0.25 * matte[2]]; + assert!(edge.iter().zip(expected).all(|(got, want)| (got - want).abs() <= 1.0 / 255.0) && edge[3] == 1.0, "{choice}: {edge:?} vs {expected:?}"); + assert_eq!(surface.rgba(1, 0)[3], 0.0); + } +} + +/// Selecting Other… must not replace None until the custom colour picker is confirmed. +#[test] +fn indexed_matte_cancel_keeps_the_previous_choice() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 2, "height": 1, "depth": 32, "background": "transparent"})).unwrap(); + let mut app = PhotocraftApp::new(session, crate::Services::default()); + let mut harness = Harness::builder().with_size(egui::vec2(900.0, 1000.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app); + PhotocraftApp::setup_context(&harness.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(harness.state_mut(), "image.mode.indexedColor").unwrap(); + harness.run_steps(3); + harness.query_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).expect("Matte dropdown").click(); + harness.run_steps(2); + harness.get_by_label("Other…").click(); + harness.run_steps(3); + + let picker = harness.state().ui.dialogs.last().expect("custom matte picker").id; + assert_ne!(picker, id); + let parent = harness.state().ui.dialogs.iter().find(|dialog| dialog.id == id).expect("Indexed Color dialog"); + assert_eq!(parent.fields.get("matte").and_then(Value::as_str), None, "opening Other… does not commit a matte"); + assert_eq!(harness.state().ui.dialogs.last().unwrap().fields["color"], "#ffffff", "the previous default still seeds the picker"); + + crate::dialogs::cancel(harness.state_mut(), picker).unwrap(); + harness.run_steps(3); + let parent = harness.state().ui.dialogs.iter().find(|dialog| dialog.id == id).expect("Indexed Color dialog"); + assert_eq!(parent.fields.get("matte").and_then(Value::as_str), None, "cancel restores the previous None choice"); + assert!(!parent.fields.contains_key("__pickColorDefault")); +} diff --git a/crates/ui-egui/src/dialogs/filter_preview_ui.rs b/crates/ui-egui/src/dialogs/filter_preview_ui.rs index f83a260b0d..7f287e9f44 100644 --- a/crates/ui-egui/src/dialogs/filter_preview_ui.rs +++ b/crates/ui-egui/src/dialogs/filter_preview_ui.rs @@ -6,7 +6,9 @@ //! click to centre the view on a document point, and press-and-hold to compare with the unfiltered //! image. The proxy is drawn scaled by its reduction factor, so 100% is one *document* pixel per //! point whatever the proxy factor. The Preview checkbox keeps toggling the on-canvas live result -//! (`canvas::ensure_filter_preview`), unchanged. +//! (`canvas::ensure_filter_preview`), unchanged. While such a dialog is on top, the image under it +//! is the preview's locator: the pointer is a small square there, and a click centres the window +//! on that document point ([`center_at`], #9648). use egui::{Color32, Rect, Sense, Stroke, Vec2, pos2, vec2}; use photocraft_doc::Document; @@ -151,6 +153,35 @@ pub(crate) fn window(app: &PhotocraftApp, dialog: u64, ui: &mut egui::Ui, f: &mu f.insert(CENTER_Y_FIELD.into(), json!(cy)); } +/// The top dialog, when it has the preview window: the image under it is then the preview's +/// locator (another dialog opened over it takes the input). Not while the image is something else +/// of the dialog's: the Blur Gallery's pins (`blur_pins`) or Replace Color's armed eyedropper. +pub(crate) fn locator(app: &PhotocraftApp) -> Option { + if crate::filter_dialog::color_eyedropper_armed(app) { + return None; + } + app.ui.dialogs.last().filter(|d| shows(&d.fields) && !crate::blur_pins::owns(&d.fields)).map(|d| d.id) +} + +/// Centre the top dialog's preview window on document point (x, y), clamped to the image, as a +/// click on the image does in Photoshop's filter dialogs (#9648). Only the dialog's private view +/// fields change: no command runs, the document and its history are untouched. `false` when no +/// dialog with a preview window is on top or the point is not finite. +pub(crate) fn center_at(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { + let Some(id) = locator(app) else { return false }; + if !(x.is_finite() && y.is_finite()) { + return false; + } + let Some(size) = app.session.active().map(|st| st.doc.size) else { return false }; + // Clamped before narrowing: a huge finite point (1e40 from `ui.pointer`) would overflow `f32` + // to infinity, which `clamp_center` reads as corrupt and puts at 0, not at the far edge. + let (cx, cy) = (x.clamp(0.0, f64::from(size.width)) as f32, y.clamp(0.0, f64::from(size.height)) as f32); + let Some(d) = app.ui.dialog_mut(id) else { return false }; + d.fields.insert(CENTER_X_FIELD.into(), json!(cx)); + d.fields.insert(CENTER_Y_FIELD.into(), json!(cy)); + true +} + /// The zoom levels the − / + buttons step through, like the Filter Gallery's. const ZOOM_STEPS: [f32; 7] = [0.125, 0.25, 0.5, 1.0, 2.0, 4.0, 8.0]; @@ -334,6 +365,7 @@ mod tests { ChannelTarget::Alpha(0), &[], &Default::default(), + Some((app.session.tools.foreground, app.session.tools.background)), ) .unwrap(); let ctx = egui::Context::default(); @@ -494,6 +526,52 @@ mod tests { assert_eq!(document_size([10, 20], 0), vec2(10.0, 20.0), "a zero factor means 1×"); } + #[test] + fn a_point_on_the_image_centres_the_top_preview_window() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + // No dialog, or one without a preview window: nothing to centre. + assert!(!center_at(&mut app, 10.0, 10.0)); + crate::dialogs::open_command_dialog(&mut app, "image.adjustments.brightnessContrast", "Brightness/Contrast…"); + assert_eq!(locator(&app), None, "an adjustment dialog has no preview window"); + app.ui.dialogs.clear(); + // Every filter dialog with the window shares the locator, Unsharp Mask and Reduce Noise too. + for command in ["filter.sharpen.unsharpMask", "filter.noise.reduceNoise"] { + let id = crate::filter_dialog::open(&mut app, command).expect("the filter opens a dialog"); + assert_eq!(locator(&app), Some(id), "{command}"); + app.ui.dialogs.clear(); + } + let id = crate::filter_dialog::open(&mut app, "filter.sharpen.smartSharpen").expect("Smart Sharpen opens a dialog"); + assert_eq!(locator(&app), Some(id), "Smart Sharpen has the preview window"); + let (revision, history) = (app.session.active().unwrap().revision, app.session.active().unwrap().history.past_len()); + let centre = |app: &PhotocraftApp| { + let f = &app.ui.dialogs.last().unwrap().fields; + (f.get(CENTER_X_FIELD).cloned(), f.get(CENTER_Y_FIELD).cloned()) + }; + assert!(center_at(&mut app, 10.5, 40.0)); + assert_eq!(centre(&app), (Some(json!(10.5)), Some(json!(40.0)))); + // Off the image it clamps to the nearest edge; a non-finite point changes nothing. + assert!(center_at(&mut app, -30.0, 999.0)); + assert_eq!(centre(&app), (Some(json!(0.0)), Some(json!(48.0)))); + assert!(!center_at(&mut app, f64::NAN, 5.0)); + assert!(!center_at(&mut app, 5.0, f64::INFINITY)); + assert_eq!(centre(&app), (Some(json!(0.0)), Some(json!(48.0)))); + // A huge but finite point (past `f32`'s range) clamps to the far edge, not to 0. + assert!(center_at(&mut app, 1e40, -1e300)); + assert_eq!(centre(&app), (Some(json!(64.0)), Some(json!(0.0)))); + assert!(center_at(&mut app, -1e300, 1e40)); + assert_eq!(centre(&app), (Some(json!(0.0)), Some(json!(48.0)))); + let st = app.session.active().unwrap(); + assert_eq!((st.revision, st.history.past_len()), (revision, history), "the document and its history are untouched"); + // The view fields are private: the command's params don't carry them. + let params = crate::filter_dialog::params_of(&app.ui.dialogs.last().unwrap().fields); + assert!(params.get(CENTER_X_FIELD).is_none() && params.get(CENTER_Y_FIELD).is_none(), "{params}"); + // A dialog opened over it takes the input. + crate::color_picker_ui::open(&mut app, "foreground"); + assert_eq!(locator(&app), None); + assert!(!center_at(&mut app, 20.0, 20.0)); + } + #[test] fn the_window_defaults_its_view_and_never_panics() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/dialogs/filter_preview_worker.rs b/crates/ui-egui/src/dialogs/filter_preview_worker.rs index 0950e67939..ad02315a8c 100644 --- a/crates/ui-egui/src/dialogs/filter_preview_worker.rs +++ b/crates/ui-egui/src/dialogs/filter_preview_worker.rs @@ -123,6 +123,7 @@ mod tests { command: "image.mode.indexedColor".into(), params: json!({"colors": colors}), k: 1, + tool_colors: ([0.0, 0.0, 0.0, 1.0], [1.0; 4]), } } diff --git a/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs b/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs index 8abbefbbd7..dd0ebca992 100644 --- a/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs +++ b/crates/ui-egui/src/dialogs/layer_style/gradient_field.rs @@ -23,6 +23,16 @@ pub(super) const KEY: &str = "stops"; /// The dialog field holding the transparency stops. pub(super) const OPACITY_KEY: &str = "opacityStops"; +/// A colour stop being dragged on the page's ramp. +#[derive(Clone, Copy, Debug)] +struct StopDrag { + /// The stop's index (it changes as the stop passes others). + index: usize, + /// The stop while it is pulled off the bar: deleted from the gradient, so the ramp and the + /// canvas show it gone; dragging back onto the bar puts it back. + removed: Option<(f32, Color)>, +} + /// Where the last drawn ramp bar is, for tests that drive it: `(effect id, bar rect)`. pub(crate) fn bar_id() -> egui::Id { egui::Id::unique("fx-gradient-bar") @@ -207,39 +217,67 @@ pub(super) fn row(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map(drag_key)); + ui.data_mut(|d| d.remove::(drag_key)); } } - let dragging: Option = ui.data(|d| d.get_temp(drag_key)); - if let (Some(i), Some(p)) = (dragging, resp.interact_pointer_pos()) { - let away = p.y > outer.bottom() + 24.0 || p.y < bar.top() - 24.0; - if resp.drag_stopped() { - ui.data_mut(|d| d.remove::(drag_key)); - if away && stops.len() > 2 { - edit(app, f, effect, disp, json!({"action": "delete", "index": i})); - ui.data_mut(|d| d.insert_temp(sel_key, 0usize)); + let dragging: Option = ui.data(|d| d.get_temp(drag_key)); + if let (Some(mut drag), Some(p)) = (dragging, resp.interact_pointer_pos()) { + let off = crate::gradient_ui::off_strip(p, bar); + let loc = loc_of(p.x); + // The release frame applies the same rule (its last move may cross the edge), then ends + // the drag. + if resp.dragged() || resp.drag_stopped() { + match drag.removed { + None if off && stops.len() > 2 => { + if let Some(stop) = stops.get(drag.index).copied() + && edit(app, f, effect, disp, json!({"action": "delete", "index": drag.index})).is_some() + { + drag.removed = Some(stop); + ui.data_mut(|d| d.insert_temp(sel_key, 0usize)); + } + } + Some((_, color)) if !off => { + let mut back = stops.clone(); + back.push((loc, color)); + back.sort_by(|a, b| a.0.total_cmp(&b.0)); + let index = back.iter().rposition(|s| s.0 == loc).unwrap_or(0); + let mut fill = fill.clone(); + if let Fill::Gradient { stops, .. } = &mut fill { + *stops = back; + } + commit(f, effect, disp, &fill); + drag = StopDrag { index, removed: None }; + ui.data_mut(|d| d.insert_temp(sel_key, index)); + } + Some(_) => {} + None => { + if (loc - stops.get(drag.index).map_or(loc, |s| s.0)).abs() > 1e-4 + && let Some(at) = edit(app, f, effect, disp, json!({"action": "move", "index": drag.index, "location": loc})) + { + drag.index = at; + ui.data_mut(|d| d.insert_temp(sel_key, at)); + } + } } - } else if resp.dragged() && !away { - let loc = loc_of(p.x); - if (loc - stops.get(i).map_or(loc, |s| s.0)).abs() > 1e-4 - && let Some(at) = edit(app, f, effect, disp, json!({"action": "move", "index": i, "location": loc})) - { - ui.data_mut(|d| d.insert_temp(drag_key, at)); - ui.data_mut(|d| d.insert_temp(sel_key, at)); + if resp.drag_stopped() { + ui.data_mut(|d| d.remove::(drag_key)); + } else { + ui.data_mut(|d| d.insert_temp(drag_key, drag)); } } } else if resp.drag_stopped() { - ui.data_mut(|d| d.remove::(drag_key)); + ui.data_mut(|d| d.remove::(drag_key)); } if resp.double_clicked() && let Some(p) = resp.interact_pointer_pos() @@ -385,6 +423,72 @@ mod tests { assert_eq!(stops_in(h.state(), parent).len(), 2); } + /// #10742: on the Gradient Overlay page a colour stop dragged down off the bar (about a + /// marker's height) disappears while it is off, is gone on release, and comes back when + /// dragged back onto the bar first. + #[test] + fn a_stop_dragged_off_the_ramp_shows_gone_and_dragging_back_cancels() { + let (mut app, parent) = dialog_app(); + let effect = crate::layer_style::effects_of(&app.ui.dialogs[0].fields)[0]["id"].as_str().unwrap().to_string(); + set_param(&mut app.ui.dialog_mut(parent).unwrap().fields, &effect, KEY, json!([[0.0, "#000000"], [0.5, "#ff0000"], [1.0, "#ffffff"]])); + let mut h = harness(app, parent); + let (_, bar): (String, Rect) = h.ctx.data(|d| d.get_temp(bar_id())).expect("the ramp was drawn"); + let mid = pos2(bar.center().x, bar.bottom() + 9.0); + let away = pos2(mid.x, mid.y + 22.0); + press(&mut h, mid); + h.event(egui::Event::PointerMoved(pos2(mid.x, mid.y + 11.0))); + h.run_steps(1); + h.event(egui::Event::PointerMoved(away)); + h.run_steps(1); + assert_eq!(stops_in(h.state(), parent).len(), 2, "off the bar the stop is gone"); + h.event(egui::Event::PointerMoved(mid)); + h.run_steps(1); + let back = stops_in(h.state(), parent); + assert_eq!(back.len(), 3, "back on the bar it returns: {back:?}"); + release(&mut h, mid); + let back = stops_in(h.state(), parent); + assert!(back.len() == 3 && (back[1].0 - 0.5).abs() < 0.01 && super::super::hex(&back[1].1) == "#ff0000", "{back:?}"); + press(&mut h, mid); + h.event(egui::Event::PointerMoved(pos2(mid.x, mid.y + 11.0))); + h.run_steps(1); + h.event(egui::Event::PointerMoved(away)); + h.run_steps(1); + release(&mut h, away); + let stops = stops_in(h.state(), parent); + assert_eq!(stops.iter().map(|s| super::super::hex(&s.1)).collect::>(), ["#000000", "#ffffff"], "{stops:?}"); + } + + /// The release frame counts: a stop that leaves the strip in the frame it is released is + /// removed, and one brought back onto the strip in that frame is kept. + #[test] + fn the_release_frame_decides_whether_a_stop_comes_off_the_ramp() { + for back in [true, false] { + let (mut app, parent) = dialog_app(); + let effect = crate::layer_style::effects_of(&app.ui.dialogs[0].fields)[0]["id"].as_str().unwrap().to_string(); + set_param(&mut app.ui.dialog_mut(parent).unwrap().fields, &effect, KEY, json!([[0.0, "#000000"], [0.5, "#ff0000"], [1.0, "#ffffff"]])); + let mut h = harness(app, parent); + let (_, bar): (String, Rect) = h.ctx.data(|d| d.get_temp(bar_id())).expect("the ramp was drawn"); + let mid = pos2(bar.center().x, bar.bottom() + 9.0); + let away = pos2(mid.x, mid.y + 30.0); + press(&mut h, mid); + h.event(egui::Event::PointerMoved(pos2(mid.x, mid.y + 11.0))); + h.run_steps(1); + if back { + h.event(egui::Event::PointerMoved(away)); + h.run_steps(1); + assert_eq!(stops_in(h.state(), parent).len(), 2, "off the strip the stop is gone"); + } + let to = if back { mid } else { away }; + // The last move and the release in one frame (`Harness::event` gives each its own). + let input = &mut h.input_mut().events; + input.push(egui::Event::PointerMoved(to)); + input.push(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + let stops = stops_in(h.state(), parent); + assert_eq!(stops.len(), if back { 3 } else { 2 }, "back {back}: {stops:?}"); + } + } + /// A preset from the Gradients panel becomes the page's stops; the Delete button and the /// Location field work on the selected stop. #[test] diff --git a/crates/ui-egui/src/dialogs/liquify_ui.rs b/crates/ui-egui/src/dialogs/liquify_ui.rs index f5263b1e81..b2853dca6d 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui.rs @@ -9,7 +9,7 @@ //! OK runs `filter.liquify` with the same strokes and gets the same field. use egui::{Align2, Color32, FontId, Pos2, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2}; -use photocraft_algo::liquify::{LiquifyField, LiquifyStroke, LiquifyTool, ProxyImage, auto_cell}; +use photocraft_algo::liquify::{LiquifyField, LiquifyStroke, LiquifyTool, MAX_LIVE_MS, ProxyImage, auto_cell}; use photocraft_doc::{DocId, Document, LayerId}; use photocraft_geom::Rect; use photocraft_raster::Surface; @@ -355,11 +355,15 @@ impl LiquifyDialog { self.last_dab = now; } + /// Continues the stroke to `p`. The point is recorded live, with the milliseconds since the + /// previous one, so the brush follows the pointer exactly and the stationary tools work by + /// real elapsed time ([`LiquifyField::stroke_segment_live`]); OK replays the same. fn extend(&mut self, p: [f64; 3], now: f64) { let Some((mut s, last)) = self.cur.take() else { return }; + let ms = if (now - self.last_dab).is_finite() { (now - self.last_dab).max(0.0) } else { 0.0 }; let t0 = crate::gpu_canvas::now_ms(); - let d = self.field.stroke_segment(&s, last, p); - s.points.push(p.to_vec()); + let d = self.field.stroke_segment_live(&s, last, p, ms); + s.points.push(vec![p[0], p[1], p[2], ms]); self.mark(d, matches!(s.tool, LiquifyTool::Freeze | LiquifyTool::Thaw)); self.render_dirty(); self.dab_ms = crate::gpu_canvas::now_ms() - t0; @@ -813,7 +817,37 @@ fn resized_brush(start_size: f32, start_density: f32, dx: f32, dy: f32, zoom: f3 /// pointer-down subtracts from the freeze mask (lasso), reverses a twirl and swaps Pucker/Bloat; /// Shift adds to the mask, same as no modifier. pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { - let now = crate::gpu_canvas::now_ms(); + pointer_at(app, ev, mods, crate::gpu_canvas::now_ms()); +} + +/// One frame's queued pointer events, at frame time `now` (ms). The frame's moves share the time +/// since the last point evenly, as they would arriving one per frame: the events are handled one +/// after another, so reading the clock for each gave the first move nearly the whole frame and +/// the rest only processing time, which changed the stationary tools' strength and where it +/// landed. After a stall the frame counts for at most [`MAX_LIVE_MS`] in all, as one point would. +fn dispatch_frame(app: &mut PhotocraftApp, events: Vec, mods: egui::Modifiers, now: f64) { + let moves = events.iter().filter(|e| matches!(e, ToolEvent::Move { .. })).count(); + let mut start = now; + if let Some(d) = app.distort.liquify.as_mut().filter(|d| d.cur.is_some()) { + if now - d.last_dab > MAX_LIVE_MS { + d.last_dab = now - MAX_LIVE_MS; + } + start = d.last_dab; + } + let mut k = 0usize; + for ev in events { + let t = if matches!(ev, ToolEvent::Move { .. }) && start.is_finite() && start < now { + k += 1; + start + (now - start) * k as f64 / moves as f64 + } else { + now + }; + pointer_at(app, ev, mods, t); + } +} + +/// [`pointer`] at time `now` (ms). +fn pointer_at(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers, now: f64) { let Some(d) = app.distort.liquify.as_mut() else { return }; match ev { ToolEvent::Down { x, y, pressure } => { @@ -1356,9 +1390,21 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { events.push(ToolEvent::Down { x: q[0], y: q[1], pressure: pr }); } else if resp.dragged() || resp.is_pointer_button_down_on() { let moved = d.cur.as_ref().is_some_and(|(_, l)| l[0] != q[0] || l[1] != q[1]); - // Stationary tools keep working while the brush is held still (30 dabs/s). - let held = d.opts.tool.is_stationary() && crate::gpu_canvas::now_ms() - d.last_dab > 33.0; - if moved || held { + // Stationary tools keep working while the brush is held still: a point every + // frame, each worth the time since the last, so the speed is the same at any + // frame rate and never stalls while the brush creeps. + let held = d.opts.tool.is_stationary(); + // Every pointer position the platform reported this frame, not just the last, so + // a quick curved stroke keeps its curve instead of being cut into one straight + // chord per frame, and a detour that returns to where it began is not dropped. + let path: Vec = + ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect()); + let detour = path.len() > 1; + for p in path.iter().take(path.len().saturating_sub(1)) { + let m = to_doc(d, area, *p); + events.push(ToolEvent::Move { x: m[0], y: m[1], pressure: pr }); + } + if moved || held || detour { events.push(ToolEvent::Move { x: q[0], y: q[1], pressure: pr }); } ctx.request_repaint(); @@ -1371,9 +1417,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { events.push(ToolEvent::Up { x: q[0], y: q[1] }); } }); - for ev in events { - pointer(app, ev, mods); - } + dispatch_frame(app, events, mods, crate::gpu_canvas::now_ms()); match action { Some("ok") => { let _ = commit(app); diff --git a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs index 533494a6ea..3e5eb2aaf8 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui/tests.rs @@ -1025,6 +1025,61 @@ fn workspaces_open_on_a_smart_object_with_its_filter_mask_targeted() { assert_eq!(sm.smart_filters.iter().map(|f| f.command.as_str()).collect::>(), ["filter.blur.gaussianBlur", photocraft_engine::distort_cmds::LIQUIFY]); } +/// The dialog's field and recorded points after a stroke of `tool` from (40, 40) through +/// (50, 40) to (60, 40) over 32 ms, its moves handed over one frame at a time (`batched` false) +/// or both in one frame (`true`). +fn timed_stroke(tool: &str, pressure: f64, batched: bool) -> (LiquifyField, Vec>) { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": tool, "size": 200, "pressure": pressure})).unwrap(); + let none = egui::Modifiers::NONE; + let (a, b) = (ToolEvent::Move { x: 50.0, y: 40.0, pressure: 1.0 }, ToolEvent::Move { x: 60.0, y: 40.0, pressure: 1.0 }); + dispatch_frame(&mut app, vec![ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }], none, 1000.0); + if batched { + dispatch_frame(&mut app, vec![a, b], none, 1032.0); + } else { + dispatch_frame(&mut app, vec![a], none, 1016.0); + dispatch_frame(&mut app, vec![b], none, 1032.0); + } + let d = app.distort.liquify.as_ref().unwrap(); + let points = d.cur.as_ref().unwrap().0.points.clone(); + (d.field.clone(), points) +} + +/// A frame's moves share its time evenly: two moves batched into one frame paint what the same +/// moves give delivered one per frame over the same time (FredApps' review of #10690). Reading +/// the clock per event gave the first move nearly the whole frame and the second only processing +/// time, so a stationary tool's strength and where it landed depended on the batching. +#[test] +fn moves_batched_in_one_frame_share_its_time() { + for (tool, pressure) in [("freeze", 10.0), ("twirlCw", 100.0), ("bloat", 50.0), ("forwardWarp", 100.0)] { + let (separate, sp) = timed_stroke(tool, pressure, false); + let (batched, bp) = timed_stroke(tool, pressure, true); + let ms = |p: &[Vec]| p.iter().map(|q| q.get(3).copied().unwrap_or(0.0)).collect::>(); + assert_eq!(ms(&bp), [0.0, 16.0, 16.0], "{tool}: each move gets half the frame"); + assert_eq!(ms(&sp), ms(&bp), "{tool}"); + assert!(separate == batched, "{tool}: batching changed the field"); + } +} + +/// After a stall, a frame's batched moves count for at most `MAX_LIVE_MS` in all, as a single +/// move after the stall does, instead of each catching up on a share of the whole stall. +#[test] +fn a_stalled_frame_counts_for_at_most_the_catch_up_limit() { + let ctx = egui::Context::default(); + let mut app = app_with_layer(); + open(&mut app, &ctx).unwrap(); + control(&mut app, &json!({"tool": "twirlCw", "size": 60})).unwrap(); + let none = egui::Modifiers::NONE; + dispatch_frame(&mut app, vec![ToolEvent::Down { x: 40.0, y: 40.0, pressure: 1.0 }], none, 1000.0); + let moves = (1..=4).map(|k| ToolEvent::Move { x: 40.0 + f64::from(k), y: 40.0, pressure: 1.0 }).collect(); + dispatch_frame(&mut app, moves, none, 3000.0); + let d = app.distort.liquify.as_ref().unwrap(); + let total: f64 = d.cur.as_ref().unwrap().0.points.iter().filter_map(|p| p.get(3)).sum(); + assert_eq!(total, MAX_LIVE_MS); +} + /// Preview off shows the image unwarped while strokes still change the field, and P turns it back /// on, as Photoshop's Liquify Preview checkbox does (#7905). Each opening starts with it on. #[test] diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 78691112c0..a34eae8ecd 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -43,6 +43,9 @@ pub struct Held { /// The Color Settings policy was already applied (a background open added it before it had /// to wait); otherwise opening applies it. pub policy_applied: bool, + /// Held by Open as Smart Object: the document holds the smart object layer already, and is + /// admitted by [`photocraft_engine::file_cmds::admit_as_smart_object`]. + pub smart_object: bool, } /// Dialog field for the high-memory confirmation prompt. @@ -323,7 +326,7 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result) -> Result "This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type?", Kind::Shape => "This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape?", - Kind::SmartObject => "This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object?", + // As measured in the reference application (#11899): lower-case "smart object". + Kind::SmartObject => { + "This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object?" + } Kind::Fill => "This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer?", } } @@ -112,7 +114,7 @@ pub fn intercept(app: &mut PhotocraftApp, tool: Tool, x: f64, y: f64, pressure: true } -/// Open the prompt for `layer`; OK rasterizes it, then `tool` paints at `at` (x, y, pressure). +/// Open the prompt for `layer`; OK rasterizes it. `tool` and `at` (x, y, pressure) only record the press that opened it. pub fn open(app: &mut PhotocraftApp, kind: Kind, layer: photocraft_doc::LayerId, tool: Tool, at: [f64; 3]) -> u64 { let mut f = Map::new(); f.insert(MARK.into(), json!(kind.key())); @@ -198,7 +200,7 @@ pub fn body(ui: &mut egui::Ui, f: &Map) { }); } -/// OK: rasterize, then paint at the click (two history states). +/// OK: rasterize the layer. The click that opened the prompt does not paint. pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { let kind = f.get(MARK).and_then(Value::as_str).and_then(Kind::from_key).ok_or("not a rasterize prompt")?; let layer = f.get("layer").and_then(Value::as_u64).ok_or("the prompt has no layer")?; @@ -206,21 +208,9 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result = f.get("at").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default(); - let (Some(tool), Some(&x), Some(&y)) = (tool, at.first(), at.get(1)) else { - return Ok(json!({ "rasterized": r, "painted": false })); - }; - let pressure = at.get(2).copied().unwrap_or(1.0) as f32; - // The same tool, layer and point as when the prompt opened. - app.ui.tool = tool; - let before = app.session.active().map(|st| st.history.past_len()); - if app.session.active().and_then(|st| st.active_layer) == Some(photocraft_doc::LayerId(layer)) && x.is_finite() && y.is_finite() { - crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: pressure.clamp(0.0, 1.0) }, egui::Modifiers::NONE); - crate::canvas::tool_event(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); - } - let painted = app.session.active().map(|st| st.history.past_len()) != before; - Ok(json!({ "rasterized": r, "painted": painted })) + // The press that opened the prompt is not replayed: Photoshop only converts the layer, the + // next click paints (#8806). + Ok(json!({ "rasterized": r })) } /// The filter prompt's answer: convert or rasterize the layer, then queue the filter for @@ -249,3 +239,7 @@ pub fn run_pending(app: &mut PhotocraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "../rasterize_prompt_text_tests.rs"] +mod rasterize_prompt_text_tests; diff --git a/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs b/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs index 9e6a10583c..b270f31ec1 100644 --- a/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs +++ b/crates/ui-egui/src/dialogs/rasterize_prompt/tests.rs @@ -3,7 +3,7 @@ use photocraft_doc::LayerContent; use serde_json::json; use super::*; -use crate::canvas::tool_event; +use crate::canvas::{ToolEvent, tool_event}; /// A document whose active layer is a `kind` layer over a white Background. fn app_with(kind: Kind) -> PhotocraftApp { @@ -46,8 +46,10 @@ fn prompt(app: &PhotocraftApp) -> Option<&crate::state::Dialog> { app.ui.dialogs.iter().find(|d| owns(&d.fields)) } +/// #8806: OK on the prompt rasterizes and adds one history state; the held click is not +/// replayed, and the next click paints with no prompt. #[test] -fn ok_rasterizes_then_paints_as_two_history_states() { +fn ok_rasterizes_without_replaying_the_click() { for kind in Kind::ALL { for tool in [Tool::Brush, Tool::Pencil] { let mut app = app_with(kind); @@ -59,12 +61,16 @@ fn ok_rasterizes_then_paints_as_two_history_states() { assert_eq!(past(&app), before, "nothing happens until the answer"); let id = d.id; let r = crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(r["painted"], json!(true), "{kind:?}/{tool:?}"); + assert!(r.get("rasterized").is_some()); assert_eq!(active_content(&app), "Pixel"); - assert_eq!(past(&app), before + 2, "{kind:?}/{tool:?}: rasterize, then paint"); + assert_eq!(past(&app), before + 1, "{kind:?}/{tool:?}: rasterize only, the held click is not replayed"); + // The held click left no paint; the next click paints. let st = app.session.active().unwrap(); let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(30, 20); - assert!(c[2] > 0.99 && c[0] < 0.01, "{kind:?}/{tool:?}: painted blue at the click: {c:?}"); + assert!(c[2] < 0.5 || c[0] > 0.5, "{kind:?}/{tool:?}: nothing painted by the held click: {c:?}"); + click(&mut app, 30.0, 20.0); + assert!(prompt(&app).is_none()); + assert_eq!(past(&app), before + 2, "{kind:?}/{tool:?}: the next click paints"); // One undo takes the paint back; the layer stays rasterized. app.session.undo(); assert_eq!(active_content(&app), "Pixel"); @@ -127,6 +133,8 @@ fn only_pixel_painting_asks() { assert!(app.session.active().unwrap().doc.layers.iter().any(|l| matches!(l.content, LayerContent::Text(_)))); } +/// A prompt with missing, stale or malformed fields returns an error instead of panicking; a +/// bad tool or point still just rasterizes. #[test] fn a_stale_or_bad_prompt_fails_gracefully() { let mut app = app_with(Kind::Type); @@ -141,13 +149,13 @@ fn a_stale_or_bad_prompt_fails_gracefully() { let id = app.ui.open_dialog(crate::state::DialogKind::Command, f.as_object().unwrap().clone()); assert!(crate::dialogs::confirm(&mut app, id).is_err(), "{f}"); } - // A bad tool or point rasterizes without painting. + // A bad tool or point still just rasterizes. let mut app = app_with(Kind::Fill); let layer = app.session.active().unwrap().active_layer.unwrap(); let id = open(&mut app, Kind::Fill, layer, Tool::Brush, [f64::NAN, 1.0, 1.0]); app.ui.dialog_mut(id).unwrap().fields.insert("tool".into(), json!("no such tool")); let r = crate::dialogs::confirm(&mut app, id).unwrap(); - assert_eq!(r["painted"], json!(false)); + assert!(r.get("rasterized").is_some()); assert_eq!(active_content(&app), "Pixel"); } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index f6ef5a1e46..c8d14130ac 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -17,6 +17,7 @@ fn filter_dialog_with_preview(background: bool) -> (PhotocraftApp, u64) { command: "filter.blur.gaussianBlur".into(), params: serde_json::json!({"radius": 4.0}), k: 1, + tool_colors: (app.session.tools.foreground, app.session.tools.background), }; app.filter_preview = Some(crate::filter_dialog::FilterPreview { key, result: result.map(std::sync::Arc::new), committing: false }); (app, id) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index bad7f725c3..ab1b090124 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -352,6 +352,23 @@ pub(crate) fn keep_newer(app: &PhotocraftApp, layout: &mut Value) { } } +/// Writes the current panels/layout snapshot now, for a discrete change such as the toolbar side, +/// whether or not the dock was drawn this frame. Only while Remember Workspace Changes is on. +pub(crate) fn persist_panels(app: &mut PhotocraftApp, ctx: &egui::Context) { + if !app.session.prefs().workspace.remember_workspace_changes { + return; + } + // Geometry still settling (OS window move, dock-edge drag, or a held pointer): keep the + // toolbar-side change pending and save it once stable, even if the dock is not drawn. + if panels_moving(app, ctx) { + set_panels_pending(ctx, true); + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + } + persist_panels_now(app); + set_panels_pending(ctx, false); +} + /// Remember the layout in the preferences once the user lets go of the mouse (Workspace › /// Remember Workspace Changes), and once panel windows the OS moves or resizes keep still. Cheap: /// a small JSON compare per frame. @@ -360,7 +377,7 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { if app.ui.docking.is_some() { app.ui.docking_kept = None; } - if !app.session.prefs().workspace.remember_workspace_changes || ctx.input(|i| i.pointer.any_down()) { + if !app.session.prefs().workspace.remember_workspace_changes || ctx.input(|i| i.pointer.any_down()) || crate::panels::dock_edge_drag_active(ctx) { return; } if native_moved(app, ctx) { @@ -375,18 +392,88 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { /// A floating panel's own window has another place than last frame. A move or resize by its OS /// title bar or edges changes the place each frame with no button down in any of the app's -/// windows. +/// windows. The answer is cached for the frame so the dock pass and `persist_panels` agree even +/// though only the first call can observe the change. fn native_moved(app: &PhotocraftApp, ctx: &egui::Context) -> bool { let places: Vec<(u64, [f32; 4])> = app.ui.docking.iter().flat_map(|workspace| workspace.layout.floating.iter().filter_map(|window| Some((window.id, window.native?)))).collect(); - let id = egui::Id::unique("dock-native-places"); + let places_id = egui::Id::unique("dock-native-places"); + let cache_id = egui::Id::unique("dock-native-moved-frame"); + let frame = ctx.cumulative_frame_nr(); ctx.data_mut(|data| { - let moved = data.get_temp::>(id).is_some_and(|last| last != places); - data.insert_temp(id, places); + // Keep any movement seen earlier in the frame, but still compare the bounds now: the + // docking UI can update them after persist_pending's early check, and the later dock save + // must not trust a stale `false`. + let cached = match data.get_temp::<(u64, bool)>(cache_id) { + Some((at, moved)) if at == frame => Some(moved), + _ => None, + }; + let previous = data.get_temp::>(places_id); + let changed = previous.as_ref().is_some_and(|last| last != &places); + let moved = cached.unwrap_or(false) || changed; + if changed || previous.is_none() { + data.insert_temp(places_id, places); + } + data.insert_temp(cache_id, (frame, moved)); moved }) } +/// Writes the panels/layout snapshot if it changed. +fn persist_panels_now(app: &mut PhotocraftApp) { + let now = snapshot(app); + if app.session.prefs().panel_layout != now { + app.session.prefs.edit(|p| p.panel_layout = now); + } +} + +/// True while a persistence pass must not record geometry: an in-progress dock-edge drag, a +/// pointer button down, or a native panel window that moved this frame. +fn panels_moving(app: &PhotocraftApp, ctx: &egui::Context) -> bool { + crate::panels::dock_edge_drag_active(ctx) || ctx.input(|i| i.pointer.any_down()) || native_moved(app, ctx) +} + +/// Whether a toolbar-side save is waiting for the dock geometry to settle. +fn panels_pending(ctx: &egui::Context) -> bool { + ctx.data(|data| data.get_temp::(egui::Id::unique("dock-persist-panels-pending")).unwrap_or(false)) +} + +/// Marks or clears the deferred toolbar-side save that [`persist_pending`] retries. +fn set_panels_pending(ctx: &egui::Context, pending: bool) { + let id = egui::Id::unique("dock-persist-panels-pending"); + ctx.data_mut(|data| { + if pending { + data.insert_temp(id, true); + } else { + data.remove::(id); + } + }); +} + +/// Retries a toolbar-side save that was deferred while geometry was moving; called every frame so +/// the save happens once the geometry is stable even when the dock and toolbar were not drawn. +pub(crate) fn persist_pending(app: &mut PhotocraftApp, ctx: &egui::Context) { + // If the dock-edge layout stopped rendering (Shift+Tab hides the dock mid-drag), its stored + // drag start cannot be cleared by the panel; drop it so deferred saves can resume. + let rendered = ctx.data(|data| data.get_temp::(egui::Id::unique("dock-edge-rendered-frame"))); + if rendered.is_none_or(|at| at + 1 < ctx.cumulative_frame_nr()) { + crate::panels::clear_dock_edge_drag(ctx); + } + if !app.session.prefs().workspace.remember_workspace_changes { + set_panels_pending(ctx, false); + return; + } + if !panels_pending(ctx) { + return; + } + if panels_moving(app, ctx) { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + return; + } + persist_panels_now(app); + set_panels_pending(ctx, false); +} + /// Restore the remembered layout at launch. Unreadable parts keep their defaults. pub fn restore(app: &mut PhotocraftApp) { if !app.session.prefs().workspace.remember_workspace_changes { @@ -423,10 +510,15 @@ pub fn apply(app: &mut PhotocraftApp, v: &Value) { Some(_) => v.get("dockingCollapsed").and_then(|v| serde_json::from_value(v.clone()).ok()).unwrap_or_default(), None => Vec::new(), }; - if let Some(mut p) = v.get("panels").and_then(|p| serde_json::from_value::(p.clone()).ok()) { + if let Some(saved) = v.get("panels") + && let Ok(mut p) = serde_json::from_value::(saved.clone()) + { // The embedding host owns these flags, including for layouts that serialize them. p.menu_bar = app.ui.panels.menu_bar; p.rail = app.ui.panels.rail; + // A layout saved before the toolbar could move (or with an unreadable side) keeps the + // current side; a valid saved side still belongs to the workspace. + p.toolbar_side = saved.get("toolbar_side").and_then(|side| serde_json::from_value(side.clone()).ok()).unwrap_or(app.ui.panels.toolbar_side); app.ui.panels = p; } if let Some(t) = v.get("dockTabs").and_then(|t| serde_json::from_value(t.clone()).ok()) { diff --git a/crates/ui-egui/src/dock/tests.rs b/crates/ui-egui/src/dock/tests.rs index d3884e20fa..08ba525e61 100644 --- a/crates/ui-egui/src/dock/tests.rs +++ b/crates/ui-egui/src/dock/tests.rs @@ -839,6 +839,35 @@ fn an_unreadable_docking_layout_is_dropped_and_the_rest_applies() { assert!(app.ui.timeline.open, "the rest of the layout still applies"); } +/// `toolbar_side` belongs to the workspace when the layout saved one; a layout saved before the +/// toolbar could move, or with an unreadable side, keeps the current side instead of `Start`. +#[test] +fn applying_a_workspace_keeps_the_toolbar_side_unless_it_saved_one() { + use crate::state::ToolbarSide; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let saved = snapshot(&app); + let cases = [ + (None, ToolbarSide::Right), + (Some(json!("sideways")), ToolbarSide::Right), + (Some(json!("left")), ToolbarSide::Left), + (Some(json!("start")), ToolbarSide::Start), + ]; + for (side, expected) in cases { + app.ui.panels.toolbar_side = ToolbarSide::Right; + app.ui.panels.brush_settings = false; + let mut saved = saved.clone(); + let panels = saved["panels"].as_object_mut().unwrap(); + panels.insert("brush_settings".into(), json!(true)); + match &side { + Some(side) => panels.insert("toolbar_side".into(), side.clone()), + None => panels.remove("toolbar_side"), + }; + apply(&mut app, &saved); + assert_eq!(app.ui.panels.toolbar_side, expected, "{side:?}"); + assert!(app.ui.panels.brush_settings, "the rest of the saved panels still apply: {side:?}"); + } +} + /// Layers panel options live in the preferences on their own (like Photoshop's Panel Options), /// so a workspace layout neither saves nor restores them. #[test] diff --git a/crates/ui-egui/src/eraser_block_right_click_tests.rs b/crates/ui-egui/src/eraser_block_right_click_tests.rs new file mode 100644 index 0000000000..73be8c8750 --- /dev/null +++ b/crates/ui-egui/src/eraser_block_right_click_tests.rs @@ -0,0 +1,123 @@ +//! #11937: with the Eraser in Block mode a plain right-click on the canvas opens the Brush · Pencil +//! · Block menu at the pointer instead of the Brush Preset picker; picking an entry sets the mode, +//! adds no history and erases nothing. Brush and Pencil mode keep the picker; Shift+right-click +//! opens the menu in every mode; with the Erase preference a right-click still erases. + +use egui_kittest::Harness; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::control::{ControlRequest, Outcome, handle}; +use crate::state::Tool; + +fn app(mode: &str) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + app.ui.tool = Tool::Eraser; + app.ui.tool_options.eraser_mode = mode.into(); + app.sync_views(); + app +} + +fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (req, _rx) = ControlRequest::new(method, params); + match handle(app, ctx, &req) { + Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } +} + +fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Value) { + call( + app, + ctx, + "ui.pointer", + json!({"button": "right", "modifiers": modifiers, "events": [{"kind": "down", "x": 20, "y": 20}, {"kind": "up", "x": 20, "y": 20}]}), + ); +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +#[test] +fn block_mode_right_click_opens_the_mode_menu() { + let ctx = egui::Context::default(); + let mut app = app("block"); + let n = steps(&app); + right_click(&mut app, &ctx, json!({})); + assert!(app.ui.brush_mode_menu.is_some(), "the Brush · Pencil · Block menu"); + assert!(app.ui.brush_picker.is_none(), "not the preset picker"); + let inspect = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(inspect["result"]["brushModeMenu"]["choices"], json!(["Brush", "Pencil", "Block"]), "{inspect}"); + // Picking Pencil sets the mode; nothing is erased and no history is added. + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id": "Pencil"}))["ok"], true); + assert_eq!(app.ui.tool_options.eraser_mode, "pencil"); + assert_eq!(steps(&app), n); + assert!(app.ui.brush_mode_menu.is_none()); +} + +#[test] +fn brush_and_pencil_mode_keep_the_picker() { + let ctx = egui::Context::default(); + for mode in ["brush", "pencil"] { + let mut app = app(mode); + right_click(&mut app, &ctx, json!({})); + assert!(app.ui.brush_picker.is_some(), "{mode}: the Brush Preset picker"); + assert!(app.ui.brush_mode_menu.is_none(), "{mode}"); + } +} + +#[test] +fn shift_right_click_opens_the_menu_in_every_mode() { + let ctx = egui::Context::default(); + for mode in ["brush", "pencil", "block"] { + let mut app = app(mode); + right_click(&mut app, &ctx, json!({"shift": true})); + assert!(app.ui.brush_mode_menu.is_some(), "{mode}"); + } +} + +#[test] +fn with_the_erase_preference_block_mode_still_erases() { + let ctx = egui::Context::default(); + let mut app = app("block"); + app.run("prefs.set", json!({"path": "tools.rightClickWithPaintingTools", "value": "erase"})).unwrap(); + call(&mut app, &ctx, "ui.pointer", json!({"button": "right", "events": [{"kind": "down", "x": 20, "y": 20}]})); + assert!(app.ui.brush_mode_menu.is_none(), "the preference's erase wins"); + assert!(app.secondary_erase || app.drag.is_some(), "a right-erase started"); +} + +/// The real mouse: a right-click on the canvas in Block mode opens the menu; Escape closes it and +/// nothing is erased. +#[test] +fn a_real_right_click_opens_the_menu_and_escape_closes_it() { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app("block"), + ); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let n = steps(h.state()); + let c = h.state().last_canvas_rect.center(); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + h.run_steps(2); + } + assert!(h.state().ui.brush_mode_menu.is_some(), "the menu at the pointer"); + assert!(h.state().ui.brush_picker.is_none()); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.brush_mode_menu.is_none(), "Escape closes it"); + assert_eq!(steps(h.state()), n, "nothing erased"); +} diff --git a/crates/ui-egui/src/eraser_range_alert_tests.rs b/crates/ui-egui/src/eraser_range_alert_tests.rs new file mode 100644 index 0000000000..8450145a80 --- /dev/null +++ b/crates/ui-egui/src/eraser_range_alert_tests.rs @@ -0,0 +1,258 @@ +//! #11938: on the Eraser's bar, Opacity, Flow and Smoothing typed out of range keep the closest +//! value and show the reference's "Closest value inserted" alert once, with OK; values in range +//! show none. The Brush's bar (not measured) keeps today's silent clamp. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::{ONE_TO_100, ZERO_TO_100}; +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +fn bar(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +/// Types `text` into the field named `label`, then Tabs out of it. +fn type_into(h: &mut Harness<'static, PhotocraftApp>, label: &str, text: &str) { + // The fields take their captions' names ("Opacity:"). + let label = &format!("{label}:"); + h.query_all_by_role(Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some(label.as_str())) + .unwrap_or_else(|| panic!("the {label} field")) + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +/// OK on the alert, as `ui.dialog.confirm` presses it (this harness draws only the bar). +fn ok(h: &mut Harness<'static, PhotocraftApp>) { + let id = h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).expect("an alert"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); +} + +fn brush(h: &Harness<'static, PhotocraftApp>) -> (f32, f32, f32) { + let b = &h.state().session.tools.brush; + ((b.opacity * 100.0).round(), (b.flow * 100.0).round(), (b.smoothing.amount * 100.0).round()) +} + +#[test] +fn eraser_opacity_flow_and_smoothing_clamp_with_the_alert() { + for (label, typed, want, alert) in [ + ("Opacity", "150", 100.0, ONE_TO_100), + ("Opacity", "0", 1.0, ONE_TO_100), + ("Flow", "150", 100.0, ONE_TO_100), + ("Flow", "0", 1.0, ONE_TO_100), + ("Smoothing", "150", 100.0, ZERO_TO_100), + ("Smoothing", "-5", 0.0, ZERO_TO_100), + ] { + let mut h = bar(Tool::Eraser); + type_into(&mut h, label, typed); + let (o, f, s) = brush(&h); + let got = match label { + "Opacity" => o, + "Flow" => f, + _ => s, + }; + assert_eq!(got, want, "{label} {typed}"); + assert_eq!(alerts(&h), [alert], "{label} {typed}: the alert, once"); + ok(&mut h); + assert!(alerts(&h).is_empty(), "{label} {typed}: OK closes it"); + let (o, f, s) = brush(&h); + assert_eq!( + match label { + "Opacity" => o, + "Flow" => f, + _ => s, + }, + want, + "{label}: the clamped value is kept" + ); + } +} + +#[test] +fn values_in_range_show_no_alert_and_the_field_keeps_working() { + let mut h = bar(Tool::Eraser); + type_into(&mut h, "Opacity", "40"); + assert_eq!(brush(&h).0, 40.0); + assert!(alerts(&h).is_empty()); + // After an alert the field still takes the keyboard. + type_into(&mut h, "Flow", "150"); + ok(&mut h); + type_into(&mut h, "Flow", "55"); + assert_eq!(brush(&h).1, 55.0); + assert!(alerts(&h).is_empty()); +} + +#[test] +fn the_alert_is_a_dialog_the_control_channel_lists() { + let mut h = bar(Tool::Eraser); + type_into(&mut h, "Smoothing", "150"); + let dialogs = serde_json::to_value(&h.state().ui.dialogs).unwrap(); + assert!(dialogs.to_string().contains(ZERO_TO_100), "{dialogs}"); +} + +#[test] +fn the_brush_bar_keeps_todays_silent_clamp() { + let mut h = bar(Tool::Brush); + type_into(&mut h, "Opacity", "150"); + assert_eq!(brush(&h).0, 100.0); + assert!(alerts(&h).is_empty(), "not measured for the Brush: no alert"); +} + +/// A value typed past the range and left while the bar is not drawn (the tool is set from outside +/// the bar, as the control channel does, and the field loses the keyboard meanwhile) shows the +/// stored value when the Eraser comes back, not the typed one, and opens no alert on the way. A +/// click on the toolbar leaves the field while the bar is drawn: see +/// `a_toolbar_click_after_a_typed_value_past_the_range_alerts_once`. +#[test] +fn a_typed_value_left_by_a_tool_switch_shows_the_stored_value() { + let mut h = bar(Tool::Eraser); + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Opacity:")).expect("the Opacity field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("150".into())); + h.run_steps(1); + let switch = |h: &mut Harness<'static, PhotocraftApp>, tool: Tool| { + h.state_mut().ui.tool = tool; + crate::paint_mouse::sync_tool_brush(h.state_mut()); + }; + switch(&mut h, Tool::Brush); + h.ctx.memory_mut(|m| { + if let Some(id) = m.focused() { + m.surrender_focus(id); + } + }); + h.run_steps(3); + assert!(alerts(&h).is_empty(), "leaving by a tool switch: no alert"); + switch(&mut h, Tool::Eraser); + h.run_steps(1); + assert!(alerts(&h).is_empty(), "back on the Eraser: no alert"); + let shown = h + .query_all_by_role(Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some("Opacity:")) + .and_then(|n| n.accesskit_node().numeric_value()); + assert_eq!(brush(&h).0, 100.0, "the stored value"); + assert_eq!(shown, Some(100.0), "the field shows the stored value"); +} + +#[test] +fn a_leading_zero_typed_key_by_key_keeps_the_text() { + // While the field has the keyboard it keeps what was typed: 0 (past 1..100) on the way to 05 + // stays 0 rather than turning into 1, so 0 then 5 is 5, not 15, and in range. + let mut h = bar(Tool::Eraser); + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Opacity:")).expect("the Opacity field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + for c in ["0", "5"] { + h.event(egui::Event::Text(c.into())); + h.run_steps(2); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(brush(&h).0, 5.0, "0 then 5 is 05"); + assert!(alerts(&h).is_empty(), "05 is in range"); +} + +#[test] +fn a_caption_scrub_past_100_does_not_alert() { + let mut h = bar(Tool::Eraser); + type_into(&mut h, "Opacity", "90"); + // The field keeps the keyboard while its caption is scrubbed from 90 past the end. + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Opacity:")).expect("the Opacity field"); + let rect = field.rect(); + field.click(); + h.run_steps(1); + // The caption sits just left of the field. + let from = egui::pos2(rect.left() - 25.0, rect.center().y); + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(1); + for k in 1..=6 { + h.event(egui::Event::PointerMoved(from + vec2(50.0 * k as f32, 0.0))); + h.run_steps(1); + } + let to = from + vec2(300.0, 0.0); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(brush(&h).0, 100.0, "the scrub reached the end"); + assert!(alerts(&h).is_empty(), "a scrub stops at 100 without an alert"); +} + +/// 150 typed into the Eraser's Opacity, then a click on the toolbar's Brush Tool: the click leaves +/// the field while the Eraser's bar is still drawn, so the value is clamped and its alert shows +/// once, as when the field is left any other way. The tool switches, and the Eraser shows the +/// stored value when it comes back. +#[test] +fn a_toolbar_click_after_a_typed_value_past_the_range_alerts_once() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = Tool::Eraser; + let mut h = Harness::builder().with_size(vec2(1800.0, 900.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + crate::panels::options_bar(app, ui); + crate::panels::toolbar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + let field = |h: &Harness<'static, PhotocraftApp>| { + h.query_all_by_role(Role::SpinButton) + .find(|n| n.accesskit_node().label().as_deref() == Some("Opacity:")) + .map(|n| (n.rect(), n.accesskit_node().numeric_value())) + }; + let click = |h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2| { + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.run_steps(1); + } + }; + let (rect, _) = field(&h).expect("the Opacity field"); + click(&mut h, rect.center()); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("150".into())); + h.run_steps(1); + let tool = |h: &Harness<'static, PhotocraftApp>, name: &str| { + h.query_all_by_role(Role::Button).find(|n| n.accesskit_node().label().is_some_and(|l| l.starts_with(name))).map(|n| n.rect().center()) + }; + let at = tool(&h, "Brush Tool").expect("the toolbar's Brush Tool"); + click(&mut h, at); + h.run_steps(3); + assert_eq!(h.state().ui.tool, Tool::Brush, "the click switches tools"); + assert_eq!(alerts(&h), [ONE_TO_100], "the typed value's alert, once"); + assert_eq!(brush(&h).0, 100.0, "the closest value is stored"); + ok(&mut h); + assert!(alerts(&h).is_empty(), "OK closes it"); + let at = tool(&h, "Eraser Tool").expect("the toolbar's Eraser Tool"); + click(&mut h, at); + h.run_steps(3); + assert_eq!(h.state().ui.tool, Tool::Eraser); + assert!(alerts(&h).is_empty(), "back on the Eraser: no alert"); + assert_eq!(field(&h).and_then(|(_, v)| v), Some(100.0), "the field shows the stored value"); +} diff --git a/crates/ui-egui/src/eyedropper_context_menu_tests.rs b/crates/ui-egui/src/eyedropper_context_menu_tests.rs new file mode 100644 index 0000000000..c2f4a1cfe7 --- /dev/null +++ b/crates/ui-egui/src/eyedropper_context_menu_tests.rs @@ -0,0 +1,179 @@ +//! #11747: a right-click on the image with the Eyedropper opens its menu: the seven Sample Sizes +//! (the current one checked), then Copy Color as HTML and Copy Color's Hex Code for the colour +//! under the pointer, read from all layers with the Sample Size, whatever the Sample setting. + +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas_tool_menu::{CanvasToolMenu, EYEDROPPER_COPY_HEX, EYEDROPPER_COPY_HTML, available, choose, mode_checked, open_at, rows}; +use crate::control::{ControlRequest, Outcome, handle}; +use crate::state::Tool; + +/// 400 × 300 white with three layers: a red (220,30,30) block at 100,100–300,250 ("Red", active), +/// a blue (30,30,220) block at 320,100–380,160 above it ("Blue"), and a green (30,160,30) block at +/// 20,20–80,80 on a 50 % opacity layer ("Green"). The Eyedropper is the tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + let block = |app: &mut PhotocraftApp, name: &str, rect: [i32; 4], color: &str, opacity: f64| { + app.run("layer.new.layer", json!({"name": name})).unwrap(); + app.run("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + if opacity < 100.0 { + app.run("layer.layerStyle.blendingOptions", json!({"opacity": opacity})).unwrap(); + } + }; + block(&mut app, "Green", [20, 20, 60, 60], "#1ea01e", 50.0); + block(&mut app, "Red", [100, 100, 200, 150], "#dc1e1e", 100.0); + block(&mut app, "Blue", [320, 100, 60, 60], "#1e1edc", 100.0); + let red = app.session.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == "Red").unwrap().2.id; + app.run("layer.select", json!({"layer": red.0})).unwrap(); + app.ui.tool = Tool::Eyedropper; + app +} + +fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (req, _rx) = ControlRequest::new(method, params); + match handle(app, ctx, &req) { + Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } +} + +/// Right-click at document point `at` (the shell's path) and return the open menu. +fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, at: [f64; 2]) -> CanvasToolMenu { + assert!(open_at(app, ctx, Tool::Eyedropper, [50.0, 50.0], Some(at)), "a menu opens"); + app.ui.canvas_tool_menu.clone().unwrap() +} + +/// What picking `command` in a freshly opened menu at `at` puts on the clipboard. +fn copied(app: &mut PhotocraftApp, at: [f64; 2], command: &str) -> Vec { + let ctx = egui::Context::default(); + right_click(app, &ctx, at); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| choose(app, ui.ctx(), command)); + out.textures_delta.clear(); + out.platform_output.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None }).collect() +} + +fn fg_bg(app: &PhotocraftApp) -> ([f32; 4], [f32; 4]) { + (app.session.tools.foreground, app.session.tools.background) +} + +#[test] +fn the_menu_lists_the_sizes_then_the_two_copy_rows_with_and_without_a_selection() { + let want = [ + "Point Sample", + "3 by 3 Average", + "5 by 5 Average", + "11 by 11 Average", + "31 by 31 Average", + "51 by 51 Average", + "101 by 101 Average", + "―", + "Copy Color as HTML", + "Copy Color's Hex Code", + ]; + for selection in [false, true] { + let mut app = app(); + if selection { + app.run("select.rect", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + } + let ctx = egui::Context::default(); + let menu = right_click(&mut app, &ctx, [200.0, 200.0]); + let labels: Vec<&str> = rows(&menu).iter().map(|r| r.map_or("―", |(l, _)| l)).collect(); + assert_eq!(labels, want, "selection {selection}"); + assert!(rows(&menu).iter().flatten().all(|(_, id)| available(&app, &menu, id)), "every row is enabled (selection {selection})"); + } +} + +#[test] +fn the_current_size_is_checked_and_picking_one_sets_it() { + let mut app = app(); + let ctx = egui::Context::default(); + let menu = right_click(&mut app, &ctx, [200.0, 200.0]); + let checked: Vec<&str> = rows(&menu).iter().flatten().map(|(_, id)| *id).filter(|id| mode_checked(&app, &menu, id)).collect(); + assert_eq!(checked, ["canvasMenu.eyedropper.size.1"], "Point Sample by default"); + choose(&mut app, &ctx, "canvasMenu.eyedropper.size.11"); + assert_eq!(app.ui.tool_options.eyedropper_size, 11, "11 by 11 Average sets the size to 11"); + assert!(app.ui.canvas_tool_menu.is_none(), "the pick closes the menu"); + let menu = right_click(&mut app, &ctx, [200.0, 200.0]); + assert!(mode_checked(&app, &menu, "canvasMenu.eyedropper.size.11") && !mode_checked(&app, &menu, "canvasMenu.eyedropper.size.1")); +} + +#[test] +fn copy_rows_copy_the_colour_under_the_right_click_in_lower_case() { + let mut app = app(); + assert_eq!(copied(&mut app, [200.0, 200.0], EYEDROPPER_COPY_HTML), ["color=\"#dc1e1e\""]); + assert_eq!(copied(&mut app, [200.0, 200.0], EYEDROPPER_COPY_HEX), ["dc1e1e"]); +} + +#[test] +fn the_copy_reads_all_layers_whatever_the_sample_setting() { + let mut app = app(); + app.ui.tool_options.eyedropper_sample = "current".into(); + // The blue is on the layer above the active Red layer. + assert_eq!(copied(&mut app, [350.0, 130.0], EYEDROPPER_COPY_HEX), ["1e1edc"]); + // The half-transparent green reads as the composite over white, not the layer's own green. + let green = copied(&mut app, [50.0, 50.0], EYEDROPPER_COPY_HEX); + let rgb = u32::from_str_radix(&green[0], 16).unwrap(); + let (r, g, b) = (rgb >> 16, (rgb >> 8) & 0xff, rgb & 0xff); + assert!((141..=143).contains(&r) && (206..=208).contains(&g) && (141..=143).contains(&b), "composite of 50 % green over white: {green:?}"); +} + +#[test] +fn the_copy_honours_the_sample_size() { + // A 3 × 3 box on the red block's corner: four of nine pixels red, the rest white. + let mut app = app(); + app.ui.tool_options.eyedropper_size = 3; + let corner = copied(&mut app, [100.5, 100.5], EYEDROPPER_COPY_HEX); + app.ui.tool_options.eyedropper_size = 1; + let point = copied(&mut app, [100.5, 100.5], EYEDROPPER_COPY_HEX); + assert_eq!(point, ["dc1e1e"]); + assert_ne!(corner, point, "the 3 by 3 average mixes in the white around the corner: {corner:?}"); +} + +#[test] +fn the_right_click_and_the_picks_change_no_colours_and_add_no_history() { + let mut app = app(); + let before = fg_bg(&app); + let steps = app.session.active().unwrap().history.past_len(); + for command in [EYEDROPPER_COPY_HTML, EYEDROPPER_COPY_HEX, "canvasMenu.eyedropper.size.5"] { + copied(&mut app, [200.0, 200.0], command); + } + assert_eq!(fg_bg(&app), before, "foreground and background unchanged"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "no history step"); +} + +#[test] +fn over_transparency_the_copy_rows_are_greyed() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 40, "height": 30, "background": "transparent"})).unwrap(); + app.ui.tool = Tool::Eyedropper; + let ctx = egui::Context::default(); + let menu = right_click(&mut app, &ctx, [10.0, 10.0]); + assert!(!available(&app, &menu, EYEDROPPER_COPY_HTML) && !available(&app, &menu, EYEDROPPER_COPY_HEX)); + assert!(available(&app, &menu, "canvasMenu.eyedropper.size.3"), "the sizes stay available"); +} + +#[test] +fn over_the_control_channel_the_menu_is_listed_and_choose_picks_a_row() { + let mut app = app(); + let ctx = egui::Context::default(); + app.sync_views(); + let r = call( + &mut app, + &ctx, + "ui.pointer", + json!({"button": "secondary", "events": [{"kind": "down", "x": 200, "y": 200}, {"kind": "up", "x": 200, "y": 200}]}), + ); + assert_eq!(r["ok"], true, "{r}"); + let inspected = call(&mut app, &ctx, "ui.inspect", json!({})); + let ids: Vec<&str> = + inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).unwrap().iter().filter_map(|e| e["id"].as_str()).collect(); + assert_eq!(ids.len(), 9, "{ids:?}"); + assert_eq!(ids[3], "canvasMenu.eyedropper.size.11"); + assert_eq!(ids[8], EYEDROPPER_COPY_HEX); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id": "canvasMenu.eyedropper.size.31"}))["ok"], true); + assert_eq!(app.ui.tool_options.eyedropper_size, 31); +} diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index cb30df9a44..cfec9c0f05 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -295,6 +295,30 @@ impl PhotocraftApp { }) } + /// File › Open as Smart Object…: the File › Open dialog (same filters, several files); each + /// chosen file opens as its own document holding one embedded smart object, in name order, + /// reporting each failure as File › Open does. + pub fn open_dialog_as_smart_object(&mut self) -> Result { + let initial_dir = last_used_dir(&self.ui.recent_files); + self.ask_file(FileDialogRequest::Open { multiple: true, initial_dir, extensions: None }, |app, answer| { + let FileDialogAnswer::Paths(paths) = answer else { return Err(UNEXPECTED.into()) }; + // Each file is a tracked open job like File › Open's, in name order. No `show_if_open`: + // the file opens as another document even when it is already open. + let mut paths: Vec = paths.iter().map(|p| crate::file_open::absolute(p)).collect(); + paths.sort_by(|a, b| crate::file_open::natural_cmp(a, b)); + let batch = crate::jobs_ui::begin_batch(app); + for (seq, path) in paths.iter().enumerate() { + let order = crate::jobs_ui::OpenOrder { batch, seq }; + if let Err(e) = crate::jobs_ui::start_open_as_smart_object(app, path, Some(order)) { + app.open_failed(&crate::file_open::display_name(path), &e); + } + } + crate::jobs_ui::end_batch(app); + app.sync_views(); + Ok(Value::Null) + }) + } + /// Opens each picked file's contents as its own document, in name order (like /// [`Self::open_paths`]), reporting each failure. fn open_contents(&mut self, mut files: Vec<(String, Vec)>) { diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 901629eb02..3896530977 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -415,7 +415,9 @@ impl PhotocraftApp { } return; } - while self.ui.transform.is_none() && self.jobs.place.is_none() && self.session.active_job().is_none() { + // A box still preparing (or its canceled job not yet handled) holds the queue too: the + // next place would lock the document before a canceled place could be taken back. + while self.ui.transform.is_none() && self.transform_preparing.is_none() && self.jobs.place.is_none() && self.session.active_job().is_none() { let Some(active) = self.session.active().map(|st| st.doc.id) else { return }; let Some((_, next)) = self.drop_places.iter().position(|(doc, _)| *doc == active).and_then(|i| self.drop_places.remove(i)) else { return; @@ -600,12 +602,12 @@ fn digit_run(it: &mut std::iter::Peekable) -> String { } #[cfg(not(target_arch = "wasm32"))] -fn absolute(p: &str) -> String { +pub(crate) fn absolute(p: &str) -> String { std::path::absolute(p).map(|a| a.to_string_lossy().to_string()).unwrap_or_else(|_| p.to_string()) } #[cfg(target_arch = "wasm32")] -fn absolute(p: &str) -> String { +pub(crate) fn absolute(p: &str) -> String { p.to_string() } diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index a617332bd1..38e07dfa85 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -1694,3 +1694,43 @@ fn queued_drop_waits_for_an_external_document_job() { assert_eq!(app.ui.transform.as_ref().and_then(|t| t.made), Some(crate::state::MadeLayer::Place)); assert!(app.drop_places.is_empty()); } + +/// File › Open as Smart Object… (#11678) asks with File › Open's dialog and opens each chosen +/// file as its own untitled document holding one embedded smart object. +#[test] +fn open_as_smart_object_dialog_opens_one_document_per_selected_file() { + let (dir, paths) = files("open-as-so", &["one.png", "two.png", "bad.png"], &png_bytes(8, 6)); + std::fs::write(&paths[2], b"not an image").unwrap(); + let (mut app, _) = app_with(vec![Some(FileDialogAnswer::Paths(paths.clone()))]); + + menus::invoke(&mut app, &egui::Context::default(), "file.openAsSmartObject", json!({})).unwrap(); + assert!(app.file_dialog_open(), "the menu item asks for files first"); + answer(&mut app); + + assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); + assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); + assert!(app.ui.notices.iter().any(|n| n.error && n.title.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// File > Open as Smart Object... runs each file as a tracked background job like File > Open +/// does: a tab per file, the documents landing in name order, untitled, failures reported. +#[test] +fn open_as_smart_object_opens_in_the_background_in_name_order() { + let ctx = egui::Context::default(); + let (dir, paths) = files("open-as-so-bg", &["two.png", "one.png", "bad.png"], &png_bytes(8, 6)); + std::fs::write(&paths[2], b"not an image").unwrap(); + let (mut app, _) = app_with(vec![Some(FileDialogAnswer::Paths(paths.clone()))]); + app.background_jobs = true; + + menus::invoke(&mut app, &ctx, "file.openAsSmartObject", json!({})).unwrap(); + answer(&mut app); + assert_eq!(app.jobs.opens.len(), 3, "a tab for each file while it opens"); + assert!(app.session.documents().is_empty(), "nothing is on the UI thread's critical path"); + + tick_until(&mut app, &ctx, |app| app.jobs.opens.is_empty()); + assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); + assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); + assert!(app.ui.notices.iter().any(|n| n.error && n.title.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/filter_preview_locator_tests.rs b/crates/ui-egui/src/filter_preview_locator_tests.rs new file mode 100644 index 0000000000..fb22379136 --- /dev/null +++ b/crates/ui-egui/src/filter_preview_locator_tests.rs @@ -0,0 +1,294 @@ +//! #9648: with a filter dialog that has a preview window on top (Smart Sharpen, Unsharp Mask…), +//! the image under it is the preview's locator, as in Photoshop: the pointer is a small square +//! there, and a click centres the dialog's preview window on that document point, without reaching +//! the tool or making a history step. Only the press counts: a drag after it leaves the window +//! where the press put it, as in the reference application. + +use egui::{Modifiers, PointerButton, Pos2, pos2, vec2}; +use egui_kittest::Harness; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::state::Tool; + +/// A 400×300 document at 400 % (so it fills the window round the dialog) with the Brush selected, +/// and the `command` filter dialog open over it when there is one. +fn harness(command: Option<&str>, rotation: f32) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.tool = Tool::Brush; + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + crate::dialogs::show(app, &ctx); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + (v.zoom, v.center, v.rotation, v.fit_pending) = (4.0, [200.0, 150.0], rotation, false); + if let Some(command) = command { + crate::filter_dialog::open(h.state_mut(), command).unwrap(); + } + h.run_steps(4); + h +} + +fn xf(h: &Harness<'static, PhotocraftApp>) -> ViewXform { + let app = h.state(); + let v = &app.ui.views[0]; + ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: false, + rotation: v.rotation, + aspect: app.ui.view.display_aspect(), + } +} + +/// The preview window's centre, in document pixels. +fn centre(h: &Harness<'static, PhotocraftApp>) -> [f64; 2] { + let f = &h.state().ui.dialogs.last().unwrap().fields; + let at = |k: &str| f.get(k).and_then(Value::as_f64).unwrap(); + [at("__pvCx"), at("__pvCy")] +} + +fn near(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 0.5 && (a[1] - b[1]).abs() < 0.5 +} + +/// The document's revision and undo depth: a click that reached a tool or ran a command moves them. +fn edits(h: &Harness<'static, PhotocraftApp>) -> (u64, usize) { + let st = h.state().session.active().unwrap(); + (st.revision, st.history.past_len()) +} + +fn button(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, down: bool) { + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE }); + h.run_steps(1); +} + +fn move_to(h: &mut Harness<'static, PhotocraftApp>, p: Pos2) { + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); +} + +fn click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2) { + move_to(h, p); + button(h, p, true); + button(h, p, false); + h.run_steps(2); +} + +#[test] +fn a_click_on_the_image_centres_the_smart_sharpen_preview() { + let mut h = harness(Some("filter.sharpen.smartSharpen"), 0.0); + assert!(crate::filter_preview_ui::locator(h.state()).is_some(), "Smart Sharpen has a preview window"); + let r = h.state().last_canvas_rect; + assert!(near(centre(&h), [200.0, 150.0]), "it opens centred: {:?}", centre(&h)); + let before = edits(&h); + + // Over the image (left of the dialog) the pointer is the locator square; over the dialog it is + // the normal pointer. + let a = pos2(r.left() + 80.0, r.bottom() - 80.0); + move_to(&mut h, a); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "the locator replaces the pointer"); + move_to(&mut h, r.center()); + assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "over the dialog it is the normal pointer"); + + // A click centres the preview on the document point under it, through the canvas transform. + click(&mut h, a); + let at = xf(&h).to_doc(a); + assert!(near(centre(&h), at), "{:?} vs {at:?}", centre(&h)); + assert!(at[0] < 150.0 && at[1] > 200.0, "the point is off the default centre: {at:?}"); + + // A drag centres it where it was pressed: neither its moves nor its release move it on. + let b = pos2(r.left() + 140.0, r.top() + 100.0); + move_to(&mut h, b); + button(&mut h, b, true); + let pressed = xf(&h).to_doc(b); + assert!(near(centre(&h), pressed), "the press centres it: {:?} vs {pressed:?}", centre(&h)); + for i in 1..=4 { + move_to(&mut h, b + (a - b) * (i as f32 / 4.0)); + assert!(near(centre(&h), pressed), "a held move leaves it: {:?} vs {pressed:?}", centre(&h)); + } + button(&mut h, a, false); + h.run_steps(2); + assert!(near(centre(&h), pressed), "the release leaves it: {:?} vs {pressed:?}", centre(&h)); + + // The Brush never painted, no command ran, and the dialog stays open. + assert_eq!(edits(&h), before, "no stroke and no history step"); + assert!(h.state().drag.is_none(), "no tool drag started"); + assert_eq!(h.state().ui.dialogs.len(), 1); + // The view fields stay out of the filter's params. + let params = crate::filter_dialog::params_of(&h.state().ui.dialogs[0].fields); + assert!(params.get("__pvCx").is_none(), "{params}"); + + // With the Hand tool the click centres the preview too (the tool doesn't matter). + h.state_mut().ui.tool = Tool::Hand; + click(&mut h, a); + assert!(near(centre(&h), xf(&h).to_doc(a)), "{:?}", centre(&h)); + assert_eq!(edits(&h), before); +} + +#[test] +fn a_click_off_the_image_centres_the_preview_on_its_nearest_edge() { + let mut h = harness(Some("filter.sharpen.unsharpMask"), 0.0); + // At 100 % the 400×300 image sits in the middle; the pasteboard's left edge is far off it. + h.state_mut().ui.views[0].zoom = 1.0; + h.run_steps(2); + let r = h.state().last_canvas_rect; + let p = pos2(r.left() + 20.0, r.center().y); + assert!(xf(&h).to_doc(p)[0] < 0.0, "the point is off the image"); + click(&mut h, p); + let [x, y] = centre(&h); + assert_eq!(x, 0.0, "clamped to the image's left edge"); + assert!((y - xf(&h).to_doc(p)[1]).abs() < 0.5, "{y}"); +} + +#[test] +fn a_rotated_view_centres_the_preview_on_the_point_under_the_pointer() { + let mut h = harness(Some("filter.sharpen.smartSharpen"), 90.0); + let r = h.state().last_canvas_rect; + let a = pos2(r.left() + 80.0, r.bottom() - 80.0); + let before = edits(&h); + click(&mut h, a); + let at = xf(&h).to_doc(a); + assert!((0.0..=400.0).contains(&at[0]) && (0.0..=300.0).contains(&at[1]), "on the image: {at:?}"); + assert!(near(centre(&h), at), "{:?} vs {at:?}", centre(&h)); + assert_eq!(edits(&h), before); +} + +#[test] +fn without_a_preview_dialog_the_click_still_reaches_the_tool() { + let mut h = harness(None, 0.0); + assert!(crate::filter_preview_ui::locator(h.state()).is_none()); + let r = h.state().last_canvas_rect; + let before = edits(&h); + click(&mut h, pos2(r.left() + 80.0, r.bottom() - 80.0)); + let after = edits(&h); + assert!(after.0 != before.0 && after.1 == before.1 + 1, "the Brush paints one stroke: {before:?} -> {after:?}"); +} + +#[test] +fn agents_centre_the_preview_with_ui_pointer_without_painting() { + let mut h = harness(Some("filter.sharpen.smartSharpen"), 0.0); + let before = edits(&h); + let ctx = egui::Context::default(); + let events = json!([{"kind": "down", "x": 60.5, "y": 250}, {"kind": "move", "x": 40, "y": 30}, {"kind": "up", "x": 40, "y": 30}]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": events})); + let _ = crate::control::handle(h.state_mut(), &ctx, &req); + assert!(near(centre(&h), [60.5, 250.0]), "the press decides, not the drag: {:?}", centre(&h)); + assert_eq!(edits(&h), before, "the Brush must not paint under the dialog"); + // Off the image the centre is clamped to it. + let events = json!([{"kind": "down", "x": 900, "y": -40}, {"kind": "up", "x": 900, "y": -40}]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": events})); + let _ = crate::control::handle(h.state_mut(), &ctx, &req); + assert!(near(centre(&h), [400.0, 0.0]), "{:?}", centre(&h)); + + // With the dialog cancelled the same gesture paints with the Brush again. + h.state_mut().ui.dialogs.clear(); + let events = json!([{"kind": "down", "x": 40, "y": 30}, {"kind": "move", "x": 60, "y": 30}, {"kind": "up", "x": 60, "y": 30}]); + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": events})); + let _ = crate::control::handle(h.state_mut(), &ctx, &req); + assert_ne!(edits(&h).0, before.0, "the Brush paints once no preview dialog is open"); +} + +/// Sends `events` as one `ui.pointer` request, then lets the frames run as between requests. +fn pointer(h: &mut Harness<'static, PhotocraftApp>, events: Value) { + let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": events})); + let _ = crate::control::handle(h.state_mut(), &egui::Context::default(), &req); + h.run_steps(2); +} + +/// Agents send a press, its moves and its release as separate requests: only the press centres +/// the preview; a hover, a move with the press held and the release leave it. +#[test] +fn ui_pointer_centres_only_on_the_press() { + let mut h = harness(Some("filter.sharpen.smartSharpen"), 0.0); + pointer(&mut h, json!([{"kind": "move", "x": 40, "y": 30}])); + // An event without a kind is a move, so a hover too. + pointer(&mut h, json!([{"x": 50, "y": 40}])); + assert!(near(centre(&h), [200.0, 150.0]), "a hover leaves the preview where it was: {:?}", centre(&h)); + pointer(&mut h, json!([{"kind": "down", "x": 40, "y": 30}])); + assert!(near(centre(&h), [40.0, 30.0]), "{:?}", centre(&h)); + pointer(&mut h, json!([{"kind": "move", "x": 80, "y": 60}])); + assert!(near(centre(&h), [40.0, 30.0]), "a move while the press is held leaves it: {:?}", centre(&h)); + pointer(&mut h, json!([{"kind": "up", "x": 80, "y": 60}])); + pointer(&mut h, json!([{"kind": "move", "x": 120, "y": 90}])); + assert!(near(centre(&h), [40.0, 30.0]), "so do the release and a later hover: {:?}", centre(&h)); +} + +/// A Brush stroke an agent began before the dialog opened still ends along its own path: its moves +/// and release reach the tool, not the locator. +#[test] +fn a_tool_gesture_begun_before_the_dialog_still_ends_under_it() { + let mut h = harness(None, 0.0); + let before = edits(&h); + pointer(&mut h, json!([{"kind": "down", "x": 40, "y": 30}, {"kind": "move", "x": 80, "y": 30}])); + assert!(h.state().drag.is_some(), "the Brush stroke is under way"); + crate::filter_dialog::open(h.state_mut(), "filter.sharpen.smartSharpen").unwrap(); + h.run_steps(2); + assert!(h.state().drag.is_some(), "the stroke is still open under the dialog"); + pointer(&mut h, json!([{"kind": "move", "x": 80, "y": 120}, {"kind": "move", "x": 120, "y": 120}])); + let points = h.state().drag.as_ref().map(|d| d.points.clone()).unwrap_or_default(); + assert!(points.iter().any(|p| p[1] > 100.0), "the moves under the dialog reached the stroke: {points:?}"); + pointer(&mut h, json!([{"kind": "up", "x": 120, "y": 120}])); + assert!(h.state().drag.is_none(), "the release reached the Brush"); + assert_eq!(edits(&h).1, before.1 + 1, "the stroke is one history step"); + assert!(near(centre(&h), [200.0, 150.0]), "the stroke's moves and release are not locator presses: {:?}", centre(&h)); +} + +/// The Crop tool keeps its frame drag apart from `app.drag`: one an agent began before the dialog +/// opened still ends along its path, so no stale drag reshapes the frame on later hovers. +#[test] +fn a_crop_drag_begun_before_the_dialog_still_ends_under_it() { + let mut h = harness(None, 0.0); + h.state_mut().ui.tool = Tool::Crop; + h.run_steps(2); + pointer(&mut h, json!([{"kind": "down", "x": 40, "y": 30}, {"kind": "move", "x": 80, "y": 60}])); + assert!(h.state().crop.drag.is_some(), "the Crop frame drag is under way"); + crate::filter_dialog::open(h.state_mut(), "filter.sharpen.smartSharpen").unwrap(); + h.run_steps(2); + pointer(&mut h, json!([{"kind": "move", "x": 160, "y": 120}])); + let r = h.state().ui.crop_rect.expect("a crop frame"); + assert!(r[2] > 150.0 && r[3] > 110.0, "the move under the dialog reached the frame before the release: {r:?}"); + pointer(&mut h, json!([{"kind": "up", "x": 160, "y": 120}])); + assert!(h.state().crop.drag.is_none(), "the release reached the Crop tool"); + let r = h.state().ui.crop_rect.expect("a crop frame"); + assert!(r[2] > 150.0 && r[3] > 110.0, "the moves under the dialog reached the frame: {r:?}"); + assert!(near(centre(&h), [200.0, 150.0]), "the drag's moves and release are not locator presses: {:?}", centre(&h)); +} + +/// A second press while an agent's Brush stroke is still open (no mouse can make one) is dropped: +/// it neither centres the preview nor reaches the Brush, and the stroke's own moves and release +/// still finish it. +#[test] +fn a_press_during_an_open_tool_gesture_is_dropped() { + let mut h = harness(None, 0.0); + let before = edits(&h); + pointer(&mut h, json!([{"kind": "down", "x": 40, "y": 30}, {"kind": "move", "x": 80, "y": 30}])); + crate::filter_dialog::open(h.state_mut(), "filter.sharpen.smartSharpen").unwrap(); + h.run_steps(2); + let points = h.state().drag.as_ref().map(|d| d.points.len()).unwrap_or_default(); + pointer(&mut h, json!([{"kind": "down", "x": 300, "y": 200}])); + assert!(near(centre(&h), [200.0, 150.0]), "the extra press doesn't centre the preview: {:?}", centre(&h)); + assert_eq!(h.state().drag.as_ref().map(|d| d.points.len()), Some(points), "nor does it reach the open stroke"); + pointer(&mut h, json!([{"kind": "move", "x": 80, "y": 120}])); + assert!(near(centre(&h), [200.0, 150.0]), "the stroke's moves are not a locator drag: {:?}", centre(&h)); + let pts = h.state().drag.as_ref().map(|d| d.points.clone()).unwrap_or_default(); + assert!(pts.iter().any(|p| p[1] > 100.0), "the move reached the stroke: {pts:?}"); + pointer(&mut h, json!([{"kind": "up", "x": 80, "y": 120}])); + assert!(h.state().drag.is_none(), "the release ended the stroke"); + assert_eq!(edits(&h).1, before.1 + 1, "the stroke is one history step"); +} diff --git a/crates/ui-egui/src/frame_stages.rs b/crates/ui-egui/src/frame_stages.rs index c2b4fc5fb9..0bc1d6c416 100644 --- a/crates/ui-egui/src/frame_stages.rs +++ b/crates/ui-egui/src/frame_stages.rs @@ -3,12 +3,13 @@ //! [`FrameStages`] is one frame's record. Each stage has one writer: the raw input hook starts //! the frame, `App::run` adds commands, the GPU canvas path adds damage tracking and budgeting, //! [`crate::gpu_canvas::Perf::record`] adds composites and uploads, and the canvas adds stroke -//! rendering. `App::ui` closes it ([`SlowFrames::finish`]). A frame over [`SLOW_FRAME_MS`] goes +//! rendering. `App::ui` closes it on the frame's last egui pass ([`SlowFrames::finish`]). A frame over [`SLOW_FRAME_MS`] goes //! into [`SlowFrames`], the last [`SLOW_FRAMES`] of them, which the control channel's `perf` //! output lists as `slowFrames`; one `info` log line per second names them. The stroke trace //! (`stroke_trace`) reads the same record, so the app times a frame in one place. //! -//! On the web `now_ms()` is 0, so no frame is ever slow and the ring stays empty. +//! The web build does the same: `now_ms()` is `performance.now()` there, and the log line goes to +//! the browser console. use std::collections::VecDeque; @@ -51,12 +52,16 @@ pub struct FrameStages { pub refresh_px: u64, /// "gpu" or "cpu": who drew the canvas. pub path: &'static str, - /// Building the UI (`App::ui`), the canvas refresh included. + /// Building the UI (`App::ui`, every egui pass of the frame), the canvas refresh included. #[serde(skip)] pub ui_ms: f64, /// Rendering stroke points (the stroke trace's `stroke`). #[serde(skip)] pub stroke_ms: f64, + /// A stroke was live in some egui pass of the frame, even one a later pass cancelled (a tool + /// change) and whose dab rendered no stroke points. + #[serde(skip)] + pub stroking: bool, /// Pointer moves the frame delivered. #[serde(skip)] pub moves: usize, @@ -66,6 +71,9 @@ pub struct FrameStages { /// The raw input hook ran for this frame. #[serde(skip)] started: bool, + /// The UI build started (a later egui pass of the frame doesn't start it again). + #[serde(skip)] + ui_started: bool, } impl FrameStages { @@ -77,7 +85,12 @@ impl FrameStages { } /// The UI build starts at `now`; `cpu_prev` is eframe's CPU time for the previous frame, in s. + /// A later egui pass of the same frame keeps the first pass's input time. pub fn ui_start(&mut self, now: f64, cpu_prev: Option) { + if self.ui_started { + return; + } + self.ui_started = true; if !self.started { self.start(now, 0); } @@ -295,6 +308,80 @@ mod app_tests { use crate::PhotocraftApp; + /// One frame of `passes` egui passes of `pass_ms` each, through the app's hooks: the raw input + /// hook starts the record once, and each pass's UI build ends in `finish_frame`. Every pass but + /// the last asks egui for another, as a sizing pass does. `stroke`: each pass renders stroke + /// points for 1 ms. + fn frame(app: &mut PhotocraftApp, ctx: &egui::Context, passes: usize, pass_ms: u64, stroke: bool) { + app.perf.stage.start(crate::gpu_canvas::now_ms(), 1); + ctx.run_ui(egui::RawInput::default(), |ui| { + let ctx = ui.ctx().clone(); + let t0 = crate::gpu_canvas::now_ms(); + app.perf.stage.ui_start(t0, None); + std::thread::sleep(std::time::Duration::from_millis(pass_ms)); + if stroke { + app.perf.stage.stroke_ms += 1.0; + } + if ctx.current_pass_index() + 1 < passes { + ctx.request_discard("a sizing pass"); + } + app.finish_frame(&ctx, crate::gpu_canvas::now_ms() - t0); + }) + .drop_without_applying_deltas(); + } + + #[test] + fn two_30_ms_passes_of_one_frame_are_one_60_ms_slow_frame() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, 2, 30, false); + let frames: Vec<_> = app.slow_frames.frames().cloned().collect(); + assert_eq!(frames.len(), 1, "{frames:?}"); + let f = &frames[0]; + assert!(f.frame_ms >= 60.0 && f.ui_ms >= 60.0, "both passes: {f:?}"); + assert!(f.input_ms < 30.0, "the first pass isn't the second's input: {f:?}"); + assert_eq!(app.perf.stage, super::FrameStages::default(), "the last pass closed the record"); + } + + #[test] + fn the_stroke_trace_gets_one_row_per_frame_not_per_pass() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.stroke_trace.output = crate::stroke_trace::Output::Stderr; + let ctx = egui::Context::default(); + for _ in 0..3 { + frame(&mut app, &ctx, 2, 1, true); + } + frame(&mut app, &ctx, 2, 1, false); + let s = app.stroke_trace.last.clone().expect("the stroke ended"); + assert_eq!(s.frames, 3, "{s:?}"); + assert_eq!(s.moves, [1.0, 1.0], "each row has its frame's moves: {s:?}"); + assert_eq!(s.stroke, [2.0, 2.0], "both passes' stroke rendering: {s:?}"); + } + + #[test] + fn a_stroke_live_only_in_a_discarded_pass_still_gets_its_frame_traced() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.stroke_trace.output = crate::stroke_trace::Output::Stderr; + let ctx = egui::Context::default(); + app.perf.stage.start(crate::gpu_canvas::now_ms(), 1); + ctx.run_ui(egui::RawInput::default(), |ui| { + let ctx = ui.ctx().clone(); + app.perf.stage.ui_start(crate::gpu_canvas::now_ms(), None); + if ctx.current_pass_index() == 0 { + // The first pass's live stroke (its `finish_frame` saw `live_stroke`), which the + // last pass cancels before rendering any stroke points. + app.perf.stage.stroking = true; + ctx.request_discard("a sizing pass"); + } + app.finish_frame(&ctx, 1.0); + }) + .drop_without_applying_deltas(); + assert!(app.live_stroke.is_none() && app.stroke_trace.last.is_none()); + frame(&mut app, &ctx, 2, 1, false); + let s = app.stroke_trace.last.clone().expect("the stroke ended"); + assert_eq!(s.frames, 1, "the frame whose stroke the last pass cancelled: {s:?}"); + } + #[test] fn an_app_frame_with_a_full_refresh_records_its_stages() { let (w, h) = (4000u64, 3000u64); diff --git a/crates/ui-egui/src/hidden_layer_tests.rs b/crates/ui-egui/src/hidden_layer_tests.rs index 806aadd8a2..ce69c21943 100644 --- a/crates/ui-egui/src/hidden_layer_tests.rs +++ b/crates/ui-egui/src/hidden_layer_tests.rs @@ -72,7 +72,13 @@ fn painting_a_hidden_layer_is_refused_at_the_press() { let n = steps(&app); tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); assert!(app.drag.is_none() && app.live_stroke.is_none(), "{tool:?}: no stroke started"); - assert!(app.ui.status.contains("target layer is hidden"), "{tool:?}: {}", app.ui.status); + // The Brush says so in its alert (#11898), the other tools in the status bar. + let alert = app.ui.dialogs.iter().any(|d| d.fields.get("message").and_then(|m| m.as_str()).is_some_and(|m| m.contains("target layer is hidden"))); + if tool == Tool::Brush { + assert!(alert, "{tool:?}: {:?}", app.ui.dialogs); + } else { + assert!(app.ui.status.contains("target layer is hidden") && app.ui.dialogs.is_empty(), "{tool:?}: {}", app.ui.status); + } tool_event(&mut app, ToolEvent::Up { x: 40.0, y: 40.0 }, egui::Modifiers::NONE); assert_eq!((bounds(&app, id), steps(&app)), (Rect::new(8, 8, 24, 24), n), "{tool:?}"); // Shown again, the same press paints. diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 1cfced87ac..3815641718 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -238,7 +238,7 @@ Plugins… المكونات الإضافية… Type… النص… Enhanced Controls… عناصر التحكم المحسنة… - Camera Raw… Camera Raw… + RAW Defaults… إعدادات RAW الافتراضية… Raw Defaults… إعدادات Raw الافتراضية… Integrations… التكاملات… AI Integrations… تكاملات الذكاء الاصطناعي… @@ -325,8 +325,8 @@ Artboard… لوح التصميم… Artboard from Group… لوح تصميم من مجموعة… Artboard from Layers… لوح تصميم من طبقات… - Layer via Copy طبقة عبر النسخ - Layer via Cut طبقة عبر القص + Layer Via Copy طبقة عبر النسخ + Layer Via Cut طبقة عبر القص Layer From Background… طبقة من الخلفية… Layer from Background… طبقة من الخلفية… Background from Layer خلفية من طبقة @@ -587,7 +587,7 @@ Last Filter آخر فلتر Filter Gallery… معرض الفلاتر… Adaptive Wide Angle… زاوية واسعة تكيفية… - Camera Raw Filter… فلتر Camera Raw… + RAW Develop Filter… فلتر معالجة RAW… Liquify… تمويع… Vanishing Point… نقطة التلاشي… Blur ضبابية @@ -929,8 +929,8 @@ Load Settings… تحميل الإعدادات… Save these settings as a Camera Raw .xmp file حفظ هذه الإعدادات كملف .xmp لـ Camera Raw Load settings from a Camera Raw .xmp file تحميل الإعدادات من ملف .xmp لـ Camera Raw - Loaded Camera Raw settings from {file} تم تحميل إعدادات Camera Raw من {file} - Loaded Camera Raw settings from {file} ({n} not supported) تم تحميل إعدادات Camera Raw من {file} ({n} غير مدعومة) + Loaded RAW Develop settings from {file} تم تحميل إعدادات معالجة RAW من {file} + Loaded RAW Develop settings from {file} ({n} not supported) تم تحميل إعدادات معالجة RAW من {file} ({n} غير مدعومة) Begin recording بدء التسجيل Bend: الانحناء: Bicubic ثنائي التكعيب @@ -958,7 +958,7 @@ Brush Reconstruct Options خيارات إعادة بناء الفرشاة Brush Tool Options خيارات أداة الفرشاة Cache Level: مستوى ذاكرة التخزين المؤقت: - Camera Raw isn't open Camera Raw غير مفتوح + RAW Develop isn't open معالجة RAW غير مفتوح Cancel إلغاء Reset إعادة تعيين Cancel (Esc) إلغاء (Esc) @@ -1936,7 +1936,7 @@ Brush preview color لون معاينة الفرشاة Cache levels مستويات ذاكرة التخزين المؤقت Cache tile size حجم بلاطة ذاكرة التخزين المؤقت - Camera Raw Defaults إعدادات Camera Raw الافتراضية + RAW Defaults إعدادات RAW الافتراضية Canvas border حدود مساحة الرسم Show canvas dots إظهار نقاط مساحة الرسم Clip thumbnails to layer bounds قصر الصور المصغرة على حدود الطبقة @@ -2023,7 +2023,6 @@ Never أبدًا Normal tip رأس عادي Open as smart object فتح ككائن ذكي - Open in camera raw فتح في Camera Raw Open documents as tabs فتح المستندات كعلامات تبويب Overscroll التمرير الزائد Performance الأداء @@ -2379,8 +2378,8 @@ 3 x 3 3 × 3 4 x 4 4 × 4 5 x 5 5 × 5 - Camera Raw Filter ({layer}) فلتر Camera Raw ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) فلتر معالجة RAW ({layer}) + RAW Develop ({name}) معالجة RAW ({name}) Edit Type تحرير النص Grid: الشبكة: Highlight Clipping Warning (O) تحذير اقتطاع الإضاءات (O) @@ -3527,6 +3526,7 @@ curves Smooth تنعيم Grayscale Ramp شريط التدرج الرمادي Current Colors الألوان الحالية Make Ramp Web Safe جعل الشريط آمنًا للويب + Scroll All Windows تمرير جميع النوافذ # Art History Brush (#213). Art History Brush فرشاة السجل الفني Art History Brush Tool أداة فرشاة السجل الفني @@ -3601,6 +3601,7 @@ curves Smooth تنعيم Pick a different document for each channel. اختر مستندًا مختلفًا لكل قناة. A picked document is no longer open. أحد المستندات المختارة لم يعد مفتوحًا. A picked document is no longer a grayscale document of the same size. أحد المستندات المختارة لم يعد مستندًا بتدرج الرمادي بالحجم نفسه. + Netscape Gray رمادي Netscape # Move tool options bar (#11381) Align top edges محاذاة الحواف العلوية Align vertical centers محاذاة المراكز الرأسية @@ -3617,3 +3618,10 @@ curves Smooth تنعيم Auto-size Canvas تحديد حجم مساحة الرسم تلقائيًا Keep Relative Position During Layer Reordering الإبقاء على الموضع النسبي عند إعادة ترتيب الطبقات Shrinkwrap Canvas on Save تقليص مساحة الرسم إلى المحتوى عند الحفظ + Move Toolbar to the Right نقل شريط الأدوات إلى اليمين + Move Toolbar to the Left نقل شريط الأدوات إلى اليسار + +# RAW Develop feature labels + Saved RAW Develop settings to {file} تم حفظ إعدادات معالجة RAW في {file} + RAW Develop معالجة RAW + RAW Develop Filter مرشح معالجة RAW diff --git a/crates/ui-egui/src/i18n/az.tsv b/crates/ui-egui/src/i18n/az.tsv index c228ba73d0..743f45a0c3 100644 --- a/crates/ui-egui/src/i18n/az.tsv +++ b/crates/ui-egui/src/i18n/az.tsv @@ -148,8 +148,8 @@ Duotone… İki ton… Duotone Duoton Trap… Rəng örtüşməsi… - Layer via Copy Kopya vasitəsilə qat - Layer via Cut Kəsərək qat yarat + Layer Via Copy Kopya vasitəsilə qat + Layer Via Cut Kəsərək qat yarat Duplicate Layer… Dublikat qat… Duplicate… Dublikat yarat… Delete Sil @@ -307,7 +307,7 @@ Last Filter Son Filtr Filter Gallery… Qalereya filtri… Liquify… Likvidləşdirin… - Camera Raw Filter… Camera Raw filtri… + RAW Develop Filter… RAW emalı filtri… Adaptive Wide Angle… Uyğunlaşan Geniş Bucaq… Lens Correction… Lens korreksiyası… Vanishing Point… Ufuq Nöqtəsi… @@ -832,8 +832,8 @@ Luminance Smoothness Parlaqlıq Hamarlığı Vignetting Vinyetləmə White Balance: As Shot Ağ Balans: Çəkiliş kimi - Camera Raw… Kamera Raw… - Camera Raw isn't open Camera Raw açıq deyil + RAW Defaults… RAW ilkin ayarları… + RAW Develop isn't open RAW emalı açıq deyil Dehaze Dehaze Texture Tekstura Focal Length Fokus Uzunluğu @@ -1092,8 +1092,6 @@ Roman Hanging Punctuation Roman asılı durğu işarələri Avoid Widows/Orphans Dul / Yetimlərdən çəkinin Compose Yarat - Adobe Single-line Composer Adobe təksətirli tərtibatçısı - Adobe Every-line Composer Adobe çoxsətirli tərtibatçısı Justification Əsaslandırma Word Spacing Söz aralığı Letter Spacing Hərf Aralığı @@ -1646,8 +1644,8 @@ Load Settings… Parametrləri yükləyin… Save these settings as a Camera Raw .xmp file Bu parametrləri Camera Raw .xmp faylı kimi yadda saxlayın Load settings from a Camera Raw .xmp file Camera Raw .xmp faylından parametrləri yükləyin - Loaded Camera Raw settings from {file} {file} -dən Camera Raw parametrləri yükləndi - Loaded Camera Raw settings from {file} ({n} not supported) {file} -dən yüklənmiş Camera Raw parametrləri ( {n} dəstəklənmir) + Loaded RAW Develop settings from {file} {file} -dən RAW emalı parametrləri yükləndi + Loaded RAW Develop settings from {file} ({n} not supported) {file} -dən yüklənmiş RAW emalı parametrləri ( {n} dəstəklənmir) After (X) Sonra (X) Original Orijinal Current Cari @@ -2212,7 +2210,7 @@ CPU (no GPU acceleration) CPU (GPU sürətləndirilməsi yoxdur) Cache levels Keş səviyyələri Cache tile size Keş kafel ölçüsü - Camera Raw Defaults Camera Raw ilkin ayarları + RAW Defaults RAW ilkin ayarları Canvas border Kətan haşiyəsi Show canvas dots Kətan nöqtələrini göstərin Clip thumbnails to layer bounds Miniatürləri qat sərhədlərinə kəsin @@ -2299,7 +2297,6 @@ Never Heç vaxt Normal tip Adi uc Open as smart object Ağıllı obyekt kimi açın - Open in camera raw Raw kamerada açın Open documents as tabs Sənədləri nişanlar kimi açın OpenGL OpenGL Orange Narıncı @@ -2440,8 +2437,8 @@ Tone Histogram Ton histoqramı Show Selected Region Seçilmiş Bölgəni göstərin cameraRaw Light İşıq - Camera Raw Filter ({layer}) Kamera Raw Filtri ( {layer} ) - Camera Raw ({name}) Kamera Raw ( {name} ) + RAW Develop Filter ({layer}) RAW emalı Filtri ( {layer} ) + RAW Develop ({name}) RAW emalı ( {name} ) Aqua Su cameraRaw Amount Miqdar cameraRaw Blacks Qara sahələr @@ -3192,13 +3189,11 @@ curves Smooth Hamarlama Adjustment Layers Tənzimləmə Layları Adjustment Properties Tənzimləmə xassələri Adjustment layers have nothing to transform Tənzimləmə qatlarinin çevriləcək heç nəsi yoxdur - Adobe PDF Presets… Hazır Adobe PDF ayarları… Adobe-rgb-compat Adobe-rgb-uyğundur Adwaita (Dark) Adwaita (Qaranlıq) Adwaita (Light) Adwaita (İşıq) After Sonra Airbrush: keeps painting while the pointer rests. Airbrush: göstərici dayanarkən rəngləməyə davam edir. - All shortcuts reset to Photoshop defaults. Bütün qısayollar Photoshop defoltlarına sıfırlanır. Altitude Hündürlük Ambience Mühit Ambient Ətraf mühit @@ -3283,8 +3278,8 @@ curves Smooth Hamarlama Brush Type Fırça növü Burlap Çuval bezi Calculations Hesablamalar - Camera Raw Kamera Raw - Camera Raw Filter Camera Raw filtri + RAW Develop RAW emalı + RAW Develop Filter RAW emalı filtri Cancel transform Çevrilməni ləğv edin Candle Light Şam işığı Canvas Size Kətan Ölçüsü @@ -3431,7 +3426,6 @@ curves Smooth Hamarlama Deep Yellow Tünd Sarı Default Foreground and Background Colors Defolt Ön və Fon Rəngləri Default Leaves Defolt yarpaqlar - Default Photoshop Size Defolt Photoshop Ölçüsü Defaults Standartlar Define Brush Preset Fırçanın Əvvəlcədən təyinini təyin edin Define Custom Shape Fərdi Formanı müəyyənləşdirin @@ -4262,7 +4256,7 @@ curves Smooth Hamarlama The file could not be saved. Faylı saxlamaq mümkün olmadı. Thickness Qalınlıq This Layer: Bu qat: - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Bu Ağıllı Obyekt davam etməzdən əvvəl rasterləşdirilməlidir. Onun məzmunu artıq redaktə edilə bilməyəcək. Ağıllı Obyekt rasterləşdirilsin? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Bu Ağıllı Obyekt davam etməzdən əvvəl rasterləşdirilməlidir. Onun məzmunu artıq redaktə edilə bilməyəcək. Ağıllı Obyekt rasterləşdirilsin? This adjustment ({key}) is kept as imported and can't be edited yet. Bu tənzimləmə ({key}) idxal edilmiş kimi saxlanılır və hələ redaktə edilə bilməz. This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Davam etməzdən əvvəl bu doldurma qatsi rasterləşdirilməlidir. Onun doldurma məzmunu artıq redaktə edilə bilməyəcək. Qat rasterləşdirilsin? This layer must be rasterized before proceeding. Davam etməzdən əvvəl bu qat rasterləşdirilməlidir. @@ -4516,9 +4510,9 @@ shape Appearance Görünüş @plural {n} document|{n} documents {n} sənəd|{n} sənəd @plural {n} pixel|{n} pixels {n} piksel|{n} piksel cameraRaw Before (Y) Əvvəl (Y) -cameraRaw Camera Raw ({name}) Kamera Raw ( {name} ) -cameraRaw Camera Raw Filter ({layer}) Kamera Raw Filtri ( {layer} ) -cameraRaw Camera Raw isn't open Camera Raw açıq deyil +cameraRaw RAW Develop ({name}) RAW emalı ( {name} ) +cameraRaw RAW Develop Filter ({layer}) RAW emalı Filtri ( {layer} ) +cameraRaw RAW Develop isn't open RAW emalı açıq deyil cameraRaw Cancel Ləğv et cameraRaw Cancelled opening {name} {name} açılışı ləğv edildi cameraRaw Cancelled {label} Ləğv edildi {label} @@ -4530,7 +4524,7 @@ cameraRaw Highlight Clipping Warning (O) Vurğulanan Kəsmə Xəbərdarlığı ( cameraRaw Highlight Priority Prioriteti vurğulayın cameraRaw Load Settings… Parametrləri yükləyin… cameraRaw Load settings from a Camera Raw .xmp file Camera Raw .xmp faylından parametrləri yükləyin -cameraRaw Loaded Camera Raw settings from {file} {file} -dən Camera Raw parametrləri yükləndi +cameraRaw Loaded RAW Develop settings from {file} {file} -dən RAW emalı parametrləri yükləndi cameraRaw Noise Reduction Səs-küyün azaldılması cameraRaw OK Oldu cameraRaw Open Aç @@ -4633,3 +4627,8 @@ smartSvg SVG editor opened. Save the SVG to update this Smart Object. SVG redakt Auto-size Canvas Kətanın ölçüsünü avtomatik təyin edin Keep Relative Position During Layer Reordering Qatları yenidən sıralayarkən nisbi mövqeyi saxlayın Shrinkwrap Canvas on Save Saxlayarkən kətanı məzmuna sıxın + Move Toolbar to the Right Alət panelini sağa köçür + Move Toolbar to the Left Alət panelini sola köçür + +# RAW Develop feature labels + Saved RAW Develop settings to {file} RAW emalı ayarları {file} faylında saxlanıldı diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 3a9cdb8137..037be0d21c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -18,7 +18,7 @@ # Conventions: Bosnian Latin script, Ijekavian, standard Bosnian vocabulary where the neighbouring # languages differ (historija, sačuvaj, tačka, datoteka, postavke), sentence case. Commands are # imperatives (Otvori…, Sačuvaj kao…), tools read "Alat …" (Alat četkica). Quotation marks „…” -# around names. Product and technology names (PhotoCraft, Camera Raw, OpenType, Lab ...) and +# around names. Product and technology names (PhotoCraft, RAW Develop, OpenType, Lab ...) and # RGB/CMYK stay as they are; the trailing "…" of dialog commands is kept. Rows Redovi @@ -216,7 +216,7 @@ Plugins… Dodaci… Type… Vrsta… Enhanced Controls… Poboljšane kontrole… - Camera Raw… Camera Raw… + RAW Defaults… Zadane RAW postavke… Raw Defaults… Zadane postavke za RAW… Integrations… Integracije… AI Integrations… AI integracije… @@ -297,8 +297,8 @@ Artboard… Radna ploča… Artboard from Group… Radna ploča iz grupe… Artboard from Layers… Radna ploča iz slojeva… - Layer via Copy Sloj kopiranjem - Layer via Cut Sloj izrezivanjem + Layer Via Copy Sloj kopiranjem + Layer Via Cut Sloj izrezivanjem Layer From Background… Sloj iz pozadine… Layer from Background… Sloj iz pozadine… Background From Layer Pozadina iz sloja @@ -531,7 +531,7 @@ Last Filter Posljednji filter Filter Gallery… Galerija filtera… Adaptive Wide Angle… Prilagodljivi široki ugao… - Camera Raw Filter… Camera Raw filter… + RAW Develop Filter… RAW obrada filter… Liquify… Ukapljivanje… Vanishing Point… Tačka nestajanja… Blur Zamućenje @@ -904,7 +904,7 @@ Brush Reconstruct Options Opcije rekonstrukcije četkicom Brush Tool Options Opcije alata četkica Cache Level: Nivo keša: - Camera Raw isn't open Camera Raw nije otvoren + RAW Develop isn't open RAW obrada nije otvoren Cancel Otkaži Cancel (Esc) Otkaži (Esc) Cancel any current edits (Esc) Otkaži sve trenutne izmjene (Esc) @@ -1860,7 +1860,7 @@ Brush preview color Boja pregleda četkice Cache levels Nivoi keša Cache tile size Veličina pločice keša - Camera Raw Defaults Zadane postavke Camera Raw + RAW Defaults Zadane RAW postavke Canvas border Okvir platna Show canvas dots Prikaži tačke platna Clip thumbnails to layer bounds Ograniči sličice na granice sloja @@ -1947,7 +1947,6 @@ Never Nikad Normal tip Normalni vrh Open as smart object Otvori kao pametni objekat - Open in camera raw Otvori u Camera Raw Open documents as tabs Otvaraj dokumente kao kartice Overscroll Prekoračenje pomjeranja Performance Performanse @@ -2358,8 +2357,6 @@ Roman Hanging Punctuation Latinična viseća interpunkcija Avoid Widows/Orphans Izbjegavaj udovice/siročad Compose Sastavi - Adobe Single-line Composer Adobe slagač jednog reda - Adobe Every-line Composer Adobe slagač svih redova Justification Obostrano poravnanje Word Spacing Razmak riječi Letter Spacing Razmak slova @@ -2614,7 +2611,6 @@ Intersect with Presijeci sa Capture Comp Zabilježi kompoziciju No Layer Comps Nema kompozicija slojeva - Adobe PDF Presets… Adobe PDF predlošci… 3D… 3D… Technology Previews… Pregledi tehnologije… Background from Layer Pozadina iz sloja @@ -2704,8 +2700,8 @@ Tone Histogram Tonski histogram Show Selected Region Prikaži odabranu regiju cameraRaw Light Svjetlo - Camera Raw Filter ({layer}) Camera Raw filter ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) RAW obrada filter ({layer}) + RAW Develop ({name}) RAW obrada ({name}) cameraRaw Lights Svijetli dijelovi cameraRaw Darks Tamni dijelovi cameraRaw Blacks Crne @@ -3728,8 +3724,8 @@ layerLabel No Color Bez boje Border Okvir Box Blur Kutijasto zamućenje Calculations Proračuni - Camera Raw Camera Raw - Camera Raw Filter Camera Raw filter + RAW Develop RAW obrada + RAW Develop Filter RAW obrada filter Channel1 Kanal1 Channel2 Kanal2 Channel3 Kanal3 @@ -4002,7 +3998,7 @@ layerLabel No Color Bez boje Scroll menu down Pomjeri meni dolje This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? Ovaj tekstualni sloj mora se rasterizirati prije nastavka. Njegov tekst više neće biti moguće uređivati. Rasterizirati tekst? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Ovaj sloj oblika mora se rasterizirati prije nastavka. Više se neće moći uređivati kao oblik. Rasterizirati oblik? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Ovaj pametni objekat mora se rasterizirati prije nastavka. Njegov sadržaj više neće biti moguće uređivati. Rasterizirati pametni objekat? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Ovaj pametni objekat mora se rasterizirati prije nastavka. Njegov sadržaj više neće biti moguće uređivati. Rasterizirati pametni objekat? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Ovaj sloj ispune mora se rasterizirati prije nastavka. Njegov sadržaj ispune više neće biti moguće uređivati. Rasterizirati sloj? This layer must be rasterized before proceeding. Ovaj sloj mora se rasterizirati prije nastavka. Color Picker (Background Color) Birač boja (boja pozadine) @@ -4079,7 +4075,6 @@ layerLabel Magenta Magenta Save Path Sačuvaj putanju cameraRaw Highlights Svijetli tonovi cameraRaw Shadows Sjene - All shortcuts reset to Photoshop defaults. Sve prečice su vraćene na zadane vrijednosti Photoshopa. Temporary Privremeno none nijedno red crvena @@ -4129,7 +4124,6 @@ cameraRaw Feather Omekšavanje ivica cameraRaw Midpoint Srednja tačka cameraRaw Roundness Zaobljenost cameraRaw Size Veličina - Default Photoshop Size Zadana veličina Photoshopa document Orientation Orijentacija Arc Lower Donji luk Arc Upper Gornji luk @@ -4154,8 +4148,8 @@ shape Appearance Izgled Load Settings… Učitaj postavke… Save these settings as a Camera Raw .xmp file Sačuvaj ove postavke kao Camera Raw .xmp datoteku Load settings from a Camera Raw .xmp file Učitaj postavke iz Camera Raw .xmp datoteke - Loaded Camera Raw settings from {file} Učitane postavke Camera Raw iz {file} - Loaded Camera Raw settings from {file} ({n} not supported) Učitane postavke Camera Raw iz {file} ({n} nije podržano) + Loaded RAW Develop settings from {file} Učitane postavke RAW obrada iz {file} + Loaded RAW Develop settings from {file} ({n} not supported) Učitane postavke RAW obrada iz {file} ({n} nije podržano) Manage submitted jobs in the system print queue Upravljajte poslanim zadacima u sistemskom redu za štampanje Pick Color From Image Uzmi boju iz slike Drag to pan · Scroll to zoom · Double-click to fit Prevucite za pomjeranje · Pomjerite točkić za zumiranje · Dvostruki klik za uklapanje @@ -4561,9 +4555,9 @@ shape Appearance Izgled @plural {n} document|{n} documents {n} dokument|{n} dokumenta|{n} dokumenata @plural {n} pixel|{n} pixels {n} piksel|{n} piksela|{n} piksela cameraRaw Before (Y) Prije (Y) -cameraRaw Camera Raw ({name}) Camera Raw ({name}) -cameraRaw Camera Raw Filter ({layer}) Camera Raw filter ({layer}) -cameraRaw Camera Raw isn't open Camera Raw nije otvoren +cameraRaw RAW Develop ({name}) RAW obrada ({name}) +cameraRaw RAW Develop Filter ({layer}) RAW obrada filter ({layer}) +cameraRaw RAW Develop isn't open RAW obrada nije otvoren cameraRaw Cancel Otkaži cameraRaw Canceled opening {name} Otkazano otvaranje {name} cameraRaw Canceled {label} Otkazano: {label} @@ -4575,7 +4569,7 @@ cameraRaw Highlight Clipping Warning (O) Upozorenje o odsijecanju svijetlih tono cameraRaw Highlight Priority Prioritet svijetlih tonova cameraRaw Load Settings… Učitaj postavke… cameraRaw Load settings from a Camera Raw .xmp file Učitaj postavke iz Camera Raw .xmp datoteke -cameraRaw Loaded Camera Raw settings from {file} Učitane postavke Camera Raw iz {file} +cameraRaw Loaded RAW Develop settings from {file} Učitane postavke RAW obrada iz {file} cameraRaw Noise Reduction Smanjenje šuma cameraRaw OK U redu cameraRaw Open Otvori @@ -4647,3 +4641,8 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Automatski promijeni veličinu platna Keep Relative Position During Layer Reordering Zadrži relativni položaj pri promjeni redoslijeda slojeva Shrinkwrap Canvas on Save Smanji platno na sadržaj pri sačuvanju + Move Toolbar to the Right Premjesti traku s alatima desno + Move Toolbar to the Left Premjesti traku s alatima lijevo + +# RAW Develop feature labels + Saved RAW Develop settings to {file} Postavke RAW obrade sačuvane u {file} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index eb8d5dc546..ee3799500f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -49,7 +49,7 @@ # Strings added to the UI after this catalog was first written (rebase onto main, 2026-10). # Gradient Editor window, opened from the options bar's gradient swatch. # Rendering mode and recovery -# Camera Raw: contextual controls and window title +# RAW Develop: contextual controls and window title @@ -87,7 +87,7 @@ # Smart Filter editors # Dynamic labels the tl! literal scanner cannot see: filter and Filter Gallery parameter names and -# choices (humanized from their keys), Camera Raw controls, render filters (Flame, Picture Frame, Tree), +# choices (humanized from their keys), RAW Develop controls, render filters (Flame, Picture Frame, Tree), # measurement columns, file info fields and the macOS application menu. Translated the same way as # above, from the plain meaning of the English label. # Select and Mask view modes (#1754) @@ -129,7 +129,7 @@ # Labels the UI looks up through a variable (tool, glyph-group, Liquify and warp names, command # parameters and choices humanized from their keys, history steps and contextual -# Camera Raw / layer labels) that other catalogs already covered. Translated the same way as +# RAW Develop / layer labels) that other catalogs already covered. Translated the same way as # above, from the plain meaning of the English label. # DDS Options (#1327) @@ -359,7 +359,7 @@ Plugins… Zásuvné moduly… Type… Text… Enhanced Controls… Rozšířené ovládání… - Camera Raw… Camera Raw… + RAW Defaults… Výchozí nastavení RAW… Raw Defaults… Výchozí nastavení Raw… Integrations… Integrace… AI Integrations… Integrace AI… @@ -448,8 +448,8 @@ Artboard… Kreslicí plocha… Artboard from Group… Kreslicí plocha ze skupiny… Artboard from Layers… Kreslicí plocha z vrstev… - Layer via Copy Vrstva kopírováním - Layer via Cut Vrstva vyjmutím + Layer Via Copy Vrstva kopírováním + Layer Via Cut Vrstva vyjmutím Layer From Background… Vrstva z pozadí… Layer from Background… Vrstva z pozadí… Background from Layer Pozadí z vrstvy @@ -692,7 +692,7 @@ Last Filter Poslední filtr Filter Gallery… Galerie filtrů… Adaptive Wide Angle… Adaptivní širokoúhlý objektiv… - Camera Raw Filter… Filtr Camera Raw… + RAW Develop Filter… Filtr Vyvolání RAW… Liquify… Zkapalnit… Vanishing Point… Úběžník… Blur Rozostření @@ -1050,8 +1050,8 @@ Load Settings… Načíst nastavení… Save these settings as a Camera Raw .xmp file Uložit toto nastavení jako soubor Camera Raw .xmp Load settings from a Camera Raw .xmp file Načíst nastavení ze souboru Camera Raw .xmp - Loaded Camera Raw settings from {file} Nastavení Camera Raw načteno ze souboru {file} - Loaded Camera Raw settings from {file} ({n} not supported) Nastavení Camera Raw načteno ze souboru {file} (nepodporováno: {n}) + Loaded RAW Develop settings from {file} Nastavení Vyvolání RAW načteno ze souboru {file} + Loaded RAW Develop settings from {file} ({n} not supported) Nastavení Vyvolání RAW načteno ze souboru {file} (nepodporováno: {n}) Begin recording Zahájit záznam Bend: Ohyb: Bicubic Bikubická @@ -1079,7 +1079,7 @@ Brush Reconstruct Options Možnosti štětce rekonstrukce Brush Tool Options Možnosti nástroje štětec Cache Level: Úroveň mezipaměti: - Camera Raw isn't open Camera Raw není otevřen + RAW Develop isn't open Vyvolání RAW není otevřen Cancel Zrušit Cancel (Esc) Zrušit (Esc) Manage submitted jobs in the system print queue Spravovat odeslané úlohy v systémové tiskové frontě @@ -2054,7 +2054,7 @@ Brush preview color Barva náhledu štětce Cache levels Úrovně mezipaměti Cache tile size Velikost dlaždice mezipaměti - Camera Raw Defaults Výchozí nastavení Camera Raw + RAW Defaults Výchozí nastavení RAW Canvas border Okraj plátna Show canvas dots Zobrazit tečky plátna Clip thumbnails to layer bounds Oříznout miniatury na hranice vrstvy @@ -2141,7 +2141,6 @@ Never Nikdy Normal tip Normální hrot Open as smart object Otevřít jako chytrý objekt - Open in camera raw Otevírat v Camera Raw Open documents as tabs Otevírat dokumenty jako záložky Overscroll Posouvání za okraj Performance Výkon @@ -2419,8 +2418,8 @@ Tone Histogram Histogram tónů Show Selected Region Zobrazit vybranou oblast cameraRaw Light Světlo - Camera Raw Filter ({layer}) Filtr Camera Raw ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) Filtr Vyvolání RAW ({layer}) + RAW Develop ({name}) Vyvolání RAW ({name}) cameraRaw Red Červené cameraRaw Orange Oranžové cameraRaw Yellow Žluté @@ -2899,8 +2898,8 @@ cameraData Lens Objektiv Burlap Pytlovina Calculations Výpočty Camera Calibration Kalibrace fotoaparátu - Camera Raw Camera Raw - Camera Raw Filter Filtr Camera Raw + RAW Develop Vyvolání RAW + RAW Develop Filter Filtr Vyvolání RAW Candle Light Plamen svíčky Canvas Size Velikost plátna Caption Popisek @@ -3807,7 +3806,7 @@ curves Smooth Vyhladit Scroll menu down Posunout nabídku dolů This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? Před pokračováním je nutné tuto textovou vrstvu rastrovat. Její text už nebude možné upravovat. Rastrovat text? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Před pokračováním je nutné tuto vrstvu tvaru rastrovat. Už ji nebude možné upravovat jako tvar. Rastrovat tvar? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Před pokračováním je nutné tento chytrý objekt rastrovat. Jeho obsah už nebude možné upravovat. Rastrovat chytrý objekt? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Před pokračováním je nutné tento chytrý objekt rastrovat. Jeho obsah už nebude možné upravovat. Rastrovat chytrý objekt? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Před pokračováním je nutné tuto vrstvu výplně rastrovat. Její výplň už nebude možné upravovat. Rastrovat vrstvu? This layer must be rasterized before proceeding. Před pokračováním je nutné tuto vrstvu rastrovat. Color Picker (Background Color) Výběr barvy (barva pozadí) @@ -4256,8 +4255,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Přechod stupňů šedi Current Colors Aktuální barvy Make Ramp Web Safe Omezit pruh na webové barvy + Scroll All Windows Posouvat všechna okna The path was kept as the Work Path Cesta byla zachována jako pracovní cesta The path was discarded Cesta byla zahozena +# Art History Brush (#213). Art History Brush Štětec umělecké historie Art History Brush Tool Nástroj štětec umělecké historie Tight Short Těsný krátký @@ -4347,6 +4348,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Pro každý kanál vyberte jiný dokument. A picked document is no longer open. Jeden z vybraných dokumentů už není otevřený. A picked document is no longer a grayscale document of the same size. Jeden z vybraných dokumentů už není dokument ve stupních šedi stejné velikosti. + Netscape Gray Šedá Netscape # Move tool options bar (#11381) Align top edges Zarovnat horní okraje Align vertical centers Zarovnat svislé středy @@ -4356,7 +4358,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Zobrazit hranice vrstvy při najetí Expand layer group on click Rozbalit skupinu vrstev kliknutím Show hover bounds from Layers Zobrazit hranice při najetí z panelu Vrstvy - Saved Camera Raw settings to {file} Nastavení Camera Raw uložena do {file} + Saved RAW Develop settings to {file} Nastavení Vyvolání RAW uložena do {file} Save the settings to each raw's sidecar without opening it Uložit nastavení do souboru sidecar každého snímku raw bez jeho otevření No settings saved: these raws can't keep a sidecar here Nic neuloženo: tyto snímky raw zde nemohou mít soubor sidecar Some settings could not be saved; the raws stay open Některá nastavení nelze uložit; snímky raw zůstávají otevřené @@ -4368,3 +4370,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Automaticky měnit velikost plátna Keep Relative Position During Layer Reordering Zachovat relativní polohu při změně pořadí vrstev Shrinkwrap Canvas on Save Při uložení zmenšit plátno na obsah + Move Toolbar to the Right Přesunout panel nástrojů doprava + Move Toolbar to the Left Přesunout panel nástrojů doleva diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index cf9105b865..37fa7f9ecd 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -185,8 +185,8 @@ Trap… Trap… # Layer - Layer via Copy Lag via kopiering - Layer via Cut Lag via udklipning + Layer Via Copy Lag via kopiering + Layer Via Cut Lag via udklipning Duplicate Layer… Duplikér lag… Duplicate… Duplikér… Delete Slet @@ -350,7 +350,7 @@ Last Filter Seneste filter Filter Gallery… Filtergalleri… Liquify… Gør flydende… - Camera Raw Filter… Camera Raw-filter… + RAW Develop Filter… RAW-fremkaldelse-filter… Adaptive Wide Angle… Adaptiv vidvinkel… Lens Correction… Objektivkorrektion… Vanishing Point… Forsvindingspunkt… @@ -875,7 +875,7 @@ Working Black Plate Arbejdssortplade Working Gray Plate Arbejdsgråplade -# Camera Raw and lens dialogs +# RAW Develop and lens dialogs Basic Grundlæggende Detail Detalje HSL/Grayscale HSL/Gråtoner @@ -905,8 +905,8 @@ Luminance Smoothness Luminansglathed Vignetting Vignettering White Balance: As Shot Hvidbalance: Som fotograferet - Camera Raw… Camera Raw… - Camera Raw isn't open Camera Raw er ikke åben + RAW Defaults… RAW-standarder… + RAW Develop isn't open RAW-fremkaldelse er ikke åben Dehaze Fjern dis Texture Tekstur Focal Length Brændvidde @@ -1177,8 +1177,6 @@ Roman Hanging Punctuation Romersk hængende tegnsætning Avoid Widows/Orphans Undgå enlige linjer Compose Komponér - Adobe Single-line Composer Adobe-enkeltlinjeopsætter - Adobe Every-line Composer Adobe-flerlinjeopsætter Justification Justering Word Spacing Ordafstand Letter Spacing Bogstavafstand @@ -1760,8 +1758,8 @@ Load Settings… Indlæs indstillinger… Save these settings as a Camera Raw .xmp file Gem disse indstillinger som en Camera Raw .xmp-fil Load settings from a Camera Raw .xmp file Indlæs indstillinger fra en Camera Raw .xmp-fil - Loaded Camera Raw settings from {file} Indlæste Camera Raw-indstillinger fra {file} - Loaded Camera Raw settings from {file} ({n} not supported) Indlæste Camera Raw-indstillinger fra {file} ({n} understøttes ikke) + Loaded RAW Develop settings from {file} Indlæste RAW-fremkaldelse-indstillinger fra {file} + Loaded RAW Develop settings from {file} ({n} not supported) Indlæste RAW-fremkaldelse-indstillinger fra {file} ({n} understøttes ikke) After (X) Efter (X) Original Original Current Aktuel @@ -2348,7 +2346,7 @@ CPU (no GPU acceleration) CPU (ingen GPU-acceleration) Cache levels Cacheniveauer Cache tile size Flisestørrelse for cache - Camera Raw Defaults Camera Raw-standarder + RAW Defaults RAW-standarder Canvas border Lærredskant Show canvas dots Vis lærredsprikker Clip thumbnails to layer bounds Klip miniaturer til laggrænser @@ -2440,7 +2438,6 @@ Never Aldrig Normal tip Normal spids Open as smart object Åbn som smartobjekt - Open in camera raw Åbn i Camera Raw Open documents as tabs Åbn dokumenter som faner OpenGL OpenGL Orange Orange @@ -2581,9 +2578,9 @@ Tone Histogram Tonehistogram Show Selected Region Vis markeret område cameraRaw Light Lys -# Camera Raw: contextual controls and window title - Camera Raw Filter ({layer}) Camera Raw-filter ({layer}) - Camera Raw ({name}) Camera Raw ({name}) +# RAW Develop: contextual controls and window title + RAW Develop Filter ({layer}) RAW-fremkaldelse-filter ({layer}) + RAW Develop ({name}) RAW-fremkaldelse ({name}) Aqua Turkis cameraRaw Amount Mængde cameraRaw Blacks Sorte @@ -3388,7 +3385,7 @@ curves Smooth Udjævn {name} was changed by another app after it was opened or saved here. {name} blev ændret af et andet program, efter at den blev åbnet eller gemt her. Replace it with this document, or cancel and use File › Save As to keep both. Erstat den med dette dokument, eller annullér, og brug Filer › Gem som for at beholde begge. -# Dynamic UI labels (fourth pass): filter and adjustment parameters, Camera Raw panels, +# Dynamic UI labels (fourth pass): filter and adjustment parameters, RAW Develop panels, # lighting, History/Layers/paths/channels menus, metadata, System Info, status templates and # dialog text that other catalogs already carry. Written from the meaning of the English labels # in the ordinary Russian graphics-editor vocabulary; no proprietary resource consulted. @@ -3414,13 +3411,11 @@ curves Smooth Udjævn Adjustment Layers Justeringslag Adjustment Properties Justeringsegenskaber Adjustment layers have nothing to transform Justeringslag har intet at transformere - Adobe PDF Presets… Adobe PDF-forudindstillinger… Adobe-rgb-compat Adobe-rgb-kompat Adwaita (Dark) Adwaita (mørk) Adwaita (Light) Adwaita (lys) After Efter Airbrush: keeps painting while the pointer rests. Airbrush: bliver ved med at male, mens markøren hviler. - All shortcuts reset to Photoshop defaults. Alle genveje er nulstillet til Photoshop-standarderne. Altitude Højde Ambience Ambiance Ambient Omgivende @@ -3505,8 +3500,8 @@ curves Smooth Udjævn Brush Type Penseltype Burlap Sækkelærred Calculations Beregninger - Camera Raw Camera Raw - Camera Raw Filter Camera Raw-filter + RAW Develop RAW-fremkaldelse + RAW Develop Filter RAW-fremkaldelse-filter Cancel transform Annullér transformering Candle Light Stearinlys Canvas Size Lærredsstørrelse @@ -3653,7 +3648,6 @@ curves Smooth Udjævn Deep Yellow Dyb gul Default Foreground and Background Colors Standard forgrunds- og baggrundsfarver Default Leaves Standardblade - Default Photoshop Size Photoshop-standardstørrelse Defaults Standardindstillinger Define Brush Preset Definér penselforudindstilling Define Custom Shape Definér brugerdefineret form @@ -4493,7 +4487,7 @@ curves Smooth Udjævn The file could not be saved. Filen kunne ikke gemmes. Thickness Tykkelse This Layer: Dette lag: - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Dette smartobjekt skal rasteriseres, før du fortsætter. Dets indhold kan ikke længere redigeres. Vil du rasterisere smartobjektet? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Dette smartobjekt skal rasteriseres, før du fortsætter. Dets indhold kan ikke længere redigeres. Vil du rasterisere smartobjektet? This adjustment ({key}) is kept as imported and can't be edited yet. Denne justering ({key}) bevares som importeret og kan ikke redigeres endnu. This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Dette udfyldningslag skal rasteriseres, før du fortsætter. Dets udfyldningsindhold kan ikke længere redigeres. Vil du rasterisere laget? This layer must be rasterized before proceeding. Dette lag skal rasteriseres, før du fortsætter. @@ -4705,6 +4699,7 @@ shape Appearance Udseende Grayscale Ramp Gråtonerampe Current Colors Aktuelle farver Make Ramp Web Safe Gør rampe websikker + Scroll All Windows Rul alle vinduer # Art History Brush (#213). Art History Brush Tool Kunstnerisk historikpenselværktøj Tight Short Stram kort @@ -4753,9 +4748,9 @@ shape Appearance Udseende @plural {n} document|{n} documents {n} dokument|{n} dokumenter @plural {n} pixel|{n} pixels {n} pixel|{n} pixels cameraRaw Before (Y) Før (Y) -cameraRaw Camera Raw ({name}) Camera Raw ({name}) -cameraRaw Camera Raw Filter ({layer}) Camera Raw-filter ({layer}) -cameraRaw Camera Raw isn't open Camera Raw er ikke åben +cameraRaw RAW Develop ({name}) RAW-fremkaldelse ({name}) +cameraRaw RAW Develop Filter ({layer}) RAW-fremkaldelse-filter ({layer}) +cameraRaw RAW Develop isn't open RAW-fremkaldelse er ikke åben cameraRaw Cancel Annullér cameraRaw Canceled opening {name} Annullerede åbning af {name} cameraRaw Canceled {label} Annullerede {label} @@ -4767,7 +4762,7 @@ cameraRaw Highlight Clipping Warning (O) Advarsel om højlysklipning (O) cameraRaw Highlight Priority Højlysprioritet cameraRaw Load Settings… Indlæs indstillinger… cameraRaw Load settings from a Camera Raw .xmp file Indlæs indstillinger fra en Camera Raw .xmp-fil -cameraRaw Loaded Camera Raw settings from {file} Indlæste Camera Raw-indstillinger fra {file} +cameraRaw Loaded RAW Develop settings from {file} Indlæste RAW-fremkaldelse-indstillinger fra {file} cameraRaw Noise Reduction Støjreduktion cameraRaw OK OK cameraRaw Open Åbn @@ -4813,6 +4808,7 @@ cameraRaw White Balance: As Shot Hvidbalance: Som fotograferet Pick a different document for each channel. Vælg et andet dokument til hver kanal. A picked document is no longer open. Et af de valgte dokumenter er ikke længere åbent. A picked document is no longer a grayscale document of the same size. Et af de valgte dokumenter er ikke længere et dokument i gråtoner i samme størrelse. + Netscape Gray Netscape-grå # Move tool options bar (#11381) Align top edges Juster øverste kanter Align vertical centers Juster lodrette midter @@ -4829,3 +4825,8 @@ cameraRaw White Balance: As Shot Hvidbalance: Som fotograferet Auto-size Canvas Tilpas lærredsstørrelse automatisk Keep Relative Position During Layer Reordering Bevar relativ placering ved omorganisering af lag Shrinkwrap Canvas on Save Beskær lærredet til indholdet ved lagring + Move Toolbar to the Right Flyt værktøjslinjen til højre + Move Toolbar to the Left Flyt værktøjslinjen til venstre + +# RAW Develop feature labels + Saved RAW Develop settings to {file} RAW-fremkaldelsesindstillinger gemt i {file} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6a970a2c7a..ec3da1eb70 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -330,7 +330,7 @@ Plugins… Plug-ins… Type… Text… Enhanced Controls… Erweiterte Bedienelemente… - Camera Raw… Camera Raw… + RAW Defaults… RAW-Standardeinstellungen… Raw Defaults… RAW-Standardwerte… Integrations… Integrationen… AI Integrations… KI-Integrationen… @@ -419,8 +419,8 @@ Artboard… Zeichenbereich… Artboard from Group… Zeichenbereich aus Gruppe… Artboard from Layers… Zeichenbereich aus Ebenen… - Layer via Copy Ebene durch Kopieren - Layer via Cut Ebene durch Ausschneiden + Layer Via Copy Ebene durch Kopieren + Layer Via Cut Ebene durch Ausschneiden Layer From Background… Ebene aus Hintergrund… Layer from Background… Ebene aus Hintergrund… Background from Layer Hintergrund aus Ebene @@ -665,7 +665,7 @@ Last Filter Letzter Filter Filter Gallery… Filtergalerie… Adaptive Wide Angle… Adaptiver Weitwinkel… - Camera Raw Filter… Camera-Raw-Filter… + RAW Develop Filter… RAW-Entwicklung-Filter… Liquify… Verflüssigen… Vanishing Point… Fluchtpunkt… Blur Weichzeichnen @@ -1009,8 +1009,8 @@ Load Settings… Einstellungen laden… Save these settings as a Camera Raw .xmp file Diese Einstellungen als Camera-Raw-.xmp-Datei speichern Load settings from a Camera Raw .xmp file Einstellungen aus einer Camera-Raw-.xmp-Datei laden - Loaded Camera Raw settings from {file} Camera-Raw-Einstellungen aus {file} geladen - Loaded Camera Raw settings from {file} ({n} not supported) Camera-Raw-Einstellungen aus {file} geladen ({n} nicht unterstützt) + Loaded RAW Develop settings from {file} RAW-Entwicklung-Einstellungen aus {file} geladen + Loaded RAW Develop settings from {file} ({n} not supported) RAW-Entwicklung-Einstellungen aus {file} geladen ({n} nicht unterstützt) Begin recording Aufnahme starten Bend: Biegung: Bicubic Bikubisch @@ -1038,7 +1038,7 @@ Brush Reconstruct Options Pinsel-Rekonstruktionsoptionen Brush Tool Options Pinselwerkzeug-Optionen Cache Level: Cache-Stufe: - Camera Raw isn't open Camera Raw ist nicht geöffnet + RAW Develop isn't open RAW-Entwicklung ist nicht geöffnet Cancel Abbrechen Reset Zurücksetzen Cancel (Esc) Abbrechen (Esc) @@ -2015,7 +2015,7 @@ Brush preview color Pinselvorschau-Farbe Cache levels Cache-Stufen Cache tile size Cache-Kachelgröße - Camera Raw Defaults Camera-Raw-Standardeinstellungen + RAW Defaults RAW-Standardeinstellungen Canvas border Zeichenflächenrand Show canvas dots Punkte der Zeichenfläche anzeigen Clip thumbnails to layer bounds Miniaturbilder auf Ebenenbegrenzung beschneiden @@ -2102,7 +2102,6 @@ Never Nie Normal tip Normale Spitze Open as smart object Als Smart-Objekt öffnen - Open in camera raw In Camera Raw öffnen Open documents as tabs Dokumente als Registerkarten öffnen Overscroll Überscrollen Performance Leistung @@ -2457,8 +2456,8 @@ 3 x 3 3 x 3 4 x 4 4 x 4 5 x 5 5 x 5 - Camera Raw Filter ({layer}) Camera-Raw-Filter ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) RAW-Entwicklung-Filter ({layer}) + RAW Develop ({name}) RAW-Entwicklung ({name}) Edit Type Text bearbeiten Grid: Raster: Highlight Clipping Warning (O) Lichter-Abschneidewarnung (O) @@ -3534,8 +3533,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Graustufenbalken Current Colors Aktuelle Farben Make Ramp Web Safe Farbbalken auf Webfarben beschränken + Scroll All Windows Alle Fenster verschieben The path was kept as the Work Path Der Pfad wurde als Arbeitspfad beibehalten The path was discarded Der Pfad wurde verworfen +# Art History Brush (#213). Art History Brush Künstlerischer Protokollpinsel Art History Brush Tool Künstlerischer-Protokollpinsel-Werkzeug Tight Short Eng kurz @@ -3642,6 +3643,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Wählen Sie für jeden Kanal ein anderes Dokument. A picked document is no longer open. Ein ausgewähltes Dokument ist nicht mehr geöffnet. A picked document is no longer a grayscale document of the same size. Ein ausgewähltes Dokument ist kein Graustufen-Dokument derselben Größe mehr. + Netscape Gray Netscape-Grau # Move tool options bar (#11381) Align top edges Obere Kanten ausrichten Align vertical centers Vertikale Mitten ausrichten @@ -3651,7 +3653,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Ebenenbegrenzung beim Darüberfahren anzeigen Expand layer group on click Ebenengruppe per Klick erweitern Show hover bounds from Layers Begrenzung beim Darüberfahren aus Ebenen anzeigen - Saved Camera Raw settings to {file} Camera-Raw-Einstellungen in {file} gespeichert + Saved RAW Develop settings to {file} RAW-Entwicklung-Einstellungen in {file} gespeichert Save the settings to each raw's sidecar without opening it Die Einstellungen in der Filialdatei jeder Raw-Datei speichern, ohne sie zu öffnen No settings saved: these raws can't keep a sidecar here Nichts gespeichert: Diese Raw-Dateien können hier keine Filialdatei haben Some settings could not be saved; the raws stay open Einige Einstellungen konnten nicht gespeichert werden; die Raw-Dateien bleiben geöffnet @@ -3663,3 +3665,9 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Zeichenflächengröße automatisch anpassen Keep Relative Position During Layer Reordering Relative Position beim Neuanordnen von Ebenen beibehalten Shrinkwrap Canvas on Save Zeichenfläche beim Speichern auf den Inhalt verkleinern + Move Toolbar to the Right Werkzeugleiste nach rechts verschieben + Move Toolbar to the Left Werkzeugleiste nach links verschieben + +# RAW Develop feature labels + RAW Develop RAW-Entwicklung + RAW Develop Filter RAW-Entwicklungsfilter diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index af6353f692..f92e5b4a1b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1602,11 +1602,10 @@ Company Εταιρεία % of all commits % του συνόλου των commits Lines +/− Γραμμές +/− - Open in camera raw Άνοιγμα στο Camera Raw System title bar Γραμμή τίτλου συστήματος More documents Περισσότερα έγγραφα Developing {name} Επεξεργασία του {name} - Camera Raw ({name}) Επεξεργασία RAW ({name}) + RAW Develop ({name}) Επεξεργασία RAW ({name}) New Brush Preset… Νέα προεπιλογή πινέλου… Capture Brush Size in Preset Αποθήκευση μεγέθους πινέλου στην προεπιλογή Include Tool Settings Συμπερίληψη ρυθμίσεων εργαλείου @@ -1774,7 +1773,7 @@ Brush preview color Χρώμα προεπισκόπησης πινέλου Cache levels Επίπεδα προσωρινής μνήμης Cache tile size Μέγεθος πλακιδίου προσωρινής μνήμης - Camera Raw Defaults Προεπιλογές Camera Raw + RAW Defaults Προεπιλογές RAW Canvas border Περίγραμμα καμβά Show canvas dots Εμφάνιση κουκκίδων καμβά Clip thumbnails to layer bounds Περικοπή μικρογραφιών στα όρια του επιπέδου @@ -1927,8 +1926,8 @@ Group… Ομάδα… Artboard… Πίνακας σχεδίασης… Artboard from Group… Πίνακας σχεδίασης από ομάδα… - Layer via Copy Επίπεδο μέσω αντιγραφής - Layer via Cut Επίπεδο μέσω αποκοπής + Layer Via Copy Επίπεδο μέσω αντιγραφής + Layer Via Cut Επίπεδο μέσω αποκοπής Layer From Background… Επίπεδο από φόντο… Layer from Background… Επίπεδο από φόντο… Background From Layer Φόντο από επίπεδο @@ -2069,11 +2068,11 @@ Load Settings… Φόρτωση ρυθμίσεων… Save these settings as a Camera Raw .xmp file Αποθήκευση αυτών των ρυθμίσεων ως αρχείο Camera Raw .xmp Load settings from a Camera Raw .xmp file Φόρτωση ρυθμίσεων από αρχείο Camera Raw .xmp - Loaded Camera Raw settings from {file} Φορτώθηκαν ρυθμίσεις Camera Raw από το {file} - Loaded Camera Raw settings from {file} ({n} not supported) Φορτώθηκαν ρυθμίσεις Camera Raw από το {file} ({n} δεν υποστηρίζονται) + Loaded RAW Develop settings from {file} Φορτώθηκαν ρυθμίσεις Επεξεργασία RAW από το {file} + Loaded RAW Develop settings from {file} ({n} not supported) Φορτώθηκαν ρυθμίσεις Επεξεργασία RAW από το {file} ({n} δεν υποστηρίζονται) Blending Ανάμειξη - Camera Raw Filter ({layer}) Φίλτρο Camera Raw ({layer}) - Camera Raw isn't open Το Camera Raw δεν είναι ανοιχτό + RAW Develop Filter ({layer}) Φίλτρο Επεξεργασία RAW ({layer}) + RAW Develop isn't open Το Επεξεργασία RAW δεν είναι ανοιχτό Clarity Διαύγεια Color Detail Λεπτομέρεια χρώματος Color Grading Χρωματική διαβάθμιση @@ -2162,7 +2161,6 @@ Adds grain to the soft edges of the brush tip. Προσθέτει κόκκο στις απαλές άκρες του πινέλου. Adjust for Zoom Προσαρμογή στη μεγέθυνση Adjustment visible Η προσαρμογή είναι ορατή - Adobe PDF Presets… Προεπιλογές Adobe PDF… Adobe RGB (1998) compatible Συμβατό με Adobe RGB (1998) Advanced Blending Σύνθετες επιλογές ανάμειξης After (X) Μετά (X) @@ -2262,10 +2260,10 @@ Bulge Κυρτότητα Cache Level: Επίπεδο προσωρινής μνήμης: Calculations Υπολογισμοί - Camera Raw Επεξεργασία ακατέργαστης εικόνας - Camera Raw Filter Φίλτρο επεξεργασίας ακατέργαστης εικόνας - Camera Raw Filter… Φίλτρο επεξεργασίας ακατέργαστης εικόνας… - Camera Raw… Επεξεργασία ακατέργαστης εικόνας… + RAW Develop Επεξεργασία RAW + RAW Develop Filter Φίλτρο Επεξεργασία RAW + RAW Develop Filter… Φίλτρο Επεξεργασία RAW… + RAW Defaults… Προεπιλογές RAW… Cancel (Esc) Ακύρωση (Esc) Manage submitted jobs in the system print queue Διαχειριστείτε τις υποβληθείσες εργασίες στην ουρά εκτύπωσης του συστήματος Cancel any current edits (Esc) Ακύρωση τρεχουσών αλλαγών (Esc) @@ -4207,8 +4205,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Διαβάθμιση του γκρι Current Colors Τρέχοντα χρώματα Make Ramp Web Safe Μόνο χρώματα ιστού στη διαβάθμιση + Scroll All Windows Κύλιση όλων των παραθύρων The path was kept as the Work Path Η διαδρομή διατηρήθηκε ως διαδρομή εργασίας The path was discarded Η διαδρομή απορρίφθηκε +# Art History Brush (#213). Art History Brush Tool Πινέλο ιστορικού τέχνης (Art History Brush Tool) Tight Short Σφιχτό κοντό Tight Medium Σφιχτό μεσαίο @@ -4306,6 +4306,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Επιλέξτε διαφορετικό έγγραφο για κάθε κανάλι. A picked document is no longer open. Ένα από τα επιλεγμένα έγγραφα δεν είναι πλέον ανοιχτό. A picked document is no longer a grayscale document of the same size. Ένα από τα επιλεγμένα έγγραφα δεν είναι πλέον έγγραφο σε κλίμακα του γκρι ίδιου μεγέθους. + Netscape Gray Γκρι Netscape # Move tool options bar (#11381) Align top edges Στοίχιση πάνω άκρων Align vertical centers Στοίχιση κατακόρυφων κέντρων @@ -4315,7 +4316,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Εμφάνιση ορίων στρώσης στο πέρασμα του δείκτη Expand layer group on click Ανάπτυξη ομάδας στρώσεων με κλικ Show hover bounds from Layers Εμφάνιση ορίων στο πέρασμα από τις Στρώσεις - Saved Camera Raw settings to {file} Οι ρυθμίσεις Camera Raw αποθηκεύτηκαν στο {file} + Saved RAW Develop settings to {file} Οι ρυθμίσεις Επεξεργασία RAW αποθηκεύτηκαν στο {file} Save the settings to each raw's sidecar without opening it Αποθήκευση των ρυθμίσεων στο συνοδευτικό αρχείο κάθε raw χωρίς άνοιγμα No settings saved: these raws can't keep a sidecar here Δεν αποθηκεύτηκε τίποτα: αυτά τα raw δεν μπορούν να έχουν συνοδευτικό αρχείο εδώ Some settings could not be saved; the raws stay open Ορισμένες ρυθμίσεις δεν ήταν δυνατό να αποθηκευτούν· τα raw παραμένουν ανοιχτά @@ -4327,3 +4328,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Αυτόματη αλλαγή μεγέθους καμβά Keep Relative Position During Layer Reordering Διατήρηση σχετικής θέσης κατά την αναδιάταξη επιπέδων Shrinkwrap Canvas on Save Σμίκρυνση καμβά στο περιεχόμενο κατά την αποθήκευση + Move Toolbar to the Right Μετακίνηση γραμμής εργαλείων δεξιά + Move Toolbar to the Left Μετακίνηση γραμμής εργαλείων αριστερά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e9b758a917..4cb003c370 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -29,7 +29,7 @@ # Spanish follows the tool wording used above (Herramienta X). # Command-id override: under Edit > Purge a bare "Deshacer" reads as an action, not the history. # Rendering mode and recovery -# Camera Raw: contextual controls and window title +# RAW Develop: contextual controls and window title # About ▸ Contributors / Models (credits) # Swatches panel # Layer Style > Blending Options (Advanced Blending) @@ -54,7 +54,7 @@ # Print dialog (#2697) # Counted status messages and labels (#3454; adapted from PR #3821) # View › Guides › New Guide… › Color -# Dynamic labels (filter and adjustment parameters, Camera Raw, panels, dialogs) that the +# Dynamic labels (filter and adjustment parameters, RAW Develop, panels, dialogs) that the # other catalogs already translate # Path, channel, layer style, status and System Info labels the Czech catalog added # Actions panel: Load/Save Actions (.atn) and kept Photoshop steps @@ -296,7 +296,7 @@ Plugins… Plugins… Type… Texto… Enhanced Controls… Controles mejorados… - Camera Raw… Camera Raw… + RAW Defaults… Valores predeterminados de RAW… Raw Defaults… Valores predeterminados de Raw… Integrations… Integraciones… AI Integrations… Integraciones de IA… @@ -385,8 +385,8 @@ Artboard… Mesa de trabajo… Artboard from Group… Mesa de trabajo a partir de grupo… Artboard from Layers… Mesa de trabajo a partir de capas… - Layer via Copy Capa vía copiar - Layer via Cut Capa vía cortar + Layer Via Copy Capa vía copiar + Layer Via Cut Capa vía cortar Layer From Background… Capa a partir del fondo… Layer from Background… Capa a partir del fondo… Background from Layer Fondo a partir de capa @@ -629,7 +629,7 @@ Last Filter Último filtro Filter Gallery… Galería de filtros… Adaptive Wide Angle… Gran angular adaptable… - Camera Raw Filter… Filtro de Camera Raw… + RAW Develop Filter… Filtro de Revelado RAW… Liquify… Licuar… Vanishing Point… Punto de fuga… Blur Desenfocar @@ -983,8 +983,8 @@ Load Settings… Cargar ajustes… Save these settings as a Camera Raw .xmp file Guardar estos ajustes como archivo .xmp de Camera Raw Load settings from a Camera Raw .xmp file Cargar ajustes desde un archivo .xmp de Camera Raw - Loaded Camera Raw settings from {file} Ajustes de Camera Raw cargados desde {file} - Loaded Camera Raw settings from {file} ({n} not supported) Ajustes de Camera Raw cargados desde {file} ({n} no compatibles) + Loaded RAW Develop settings from {file} Ajustes de Revelado RAW cargados desde {file} + Loaded RAW Develop settings from {file} ({n} not supported) Ajustes de Revelado RAW cargados desde {file} ({n} no compatibles) Begin recording Iniciar grabación Bend: Curvatura: Bicubic Bicúbica @@ -1012,7 +1012,7 @@ Brush Reconstruct Options Opciones de reconstrucción del pincel Brush Tool Options Opciones de la herramienta Pincel Cache Level: Nivel de caché: - Camera Raw isn't open Camera Raw no está abierto + RAW Develop isn't open Revelado RAW no está abierto Cancel Cancelar Cancel (Esc) Cancelar (Esc) Manage submitted jobs in the system print queue Gestionar los trabajos enviados en la cola de impresión del sistema @@ -1984,7 +1984,7 @@ Brush preview color Color de vista previa del pincel Cache levels Niveles de caché Cache tile size Tamaño de tesela de caché - Camera Raw Defaults Valores predeterminados de Camera Raw + RAW Defaults Valores predeterminados de RAW Canvas border Borde del lienzo Show canvas dots Mostrar puntos del lienzo Clip thumbnails to layer bounds Recortar miniaturas a los límites de la capa @@ -2071,7 +2071,6 @@ Never Nunca Normal tip Punta normal Open as smart object Abrir como objeto inteligente - Open in camera raw Abrir en Camera Raw Open documents as tabs Abrir los documentos como pestañas Overscroll Sobredesplazamiento Performance Rendimiento @@ -2432,8 +2431,8 @@ Tone Histogram Histograma tonal Show Selected Region Mostrar región seleccionada cameraRaw Light Luz - Camera Raw Filter ({layer}) Filtro de Camera Raw ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) Filtro de Revelado RAW ({layer}) + RAW Develop ({name}) Revelado RAW ({name}) cameraRaw Lights Claros cameraRaw Darks Oscuros cameraRaw Red Rojos @@ -3030,8 +3029,6 @@ curves Smooth Suavizar Roman Hanging Punctuation Puntuación latina colgante Avoid Widows/Orphans Evitar líneas viudas y huérfanas Compose Componer - Adobe Single-line Composer Compositor de línea única de Adobe - Adobe Every-line Composer Compositor multilínea de Adobe Word Spacing Espacio entre palabras Letter Spacing Espacio entre caracteres Glyph Scaling Escala de glifos @@ -3227,7 +3224,6 @@ curves Smooth Suavizar Intersect with Intersecar con Capture Comp Capturar composición No Layer Comps No hay composiciones de capas - Adobe PDF Presets… Ajustes preestablecidos de Adobe PDF… 3D… 3D… Technology Previews… Previsualizaciones de tecnología… Add a mask (from the selection; ⌥ inverts) Añadir una máscara (a partir de la selección; ⌥ invierte) @@ -3844,8 +3840,8 @@ layerLabel No Color Sin color Border Borde Box Blur Desenfoque de cuadro Calculations Cálculos - Camera Raw Camera Raw - Camera Raw Filter Filtro de Camera Raw + RAW Develop Revelado RAW + RAW Develop Filter Filtro de Revelado RAW Channel1 Canal 1 Channel2 Canal 2 Channel3 Canal 3 @@ -4105,7 +4101,7 @@ layerLabel No Color Sin color Scroll menu down Desplazar menú hacia abajo This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? Esta capa de texto debe rasterizarse antes de continuar. Su texto dejará de ser editable. ¿Rasterizar el texto? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Esta capa de forma debe rasterizarse antes de continuar. Dejará de ser editable como forma. ¿Rasterizar la forma? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Este objeto inteligente debe rasterizarse antes de continuar. Su contenido dejará de ser editable. ¿Rasterizar el objeto inteligente? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Este objeto inteligente debe rasterizarse antes de continuar. Su contenido dejará de ser editable. ¿Rasterizar el objeto inteligente? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Esta capa de relleno debe rasterizarse antes de continuar. Su contenido de relleno dejará de ser editable. ¿Rasterizar la capa? This layer must be rasterized before proceeding. Esta capa debe rasterizarse antes de continuar. Color Picker (Background Color) Selector de color (color de fondo) @@ -4417,8 +4413,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Rampa de escala de grises Current Colors Colores actuales Make Ramp Web Safe Hacer rampa segura para web + Scroll All Windows Desplazar todas las ventanas The path was kept as the Work Path El trazado se conservó como trazado de trabajo The path was discarded El trazado se descartó +# Art History Brush (#213). Art History Brush Tool Herramienta Pincel histórico artístico Tight Short Corto apretado Tight Medium Medio apretado @@ -4506,6 +4504,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Elija un documento distinto para cada canal. A picked document is no longer open. Uno de los documentos elegidos ya no está abierto. A picked document is no longer a grayscale document of the same size. Uno de los documentos elegidos ya no es un documento en escala de grises del mismo tamaño. + Netscape Gray Gris Netscape # Move tool options bar (#11381) Align top edges Alinear bordes superiores Align vertical centers Alinear centros verticales @@ -4515,7 +4514,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Mostrar límites de capa al pasar el puntero Expand layer group on click Expandir grupo de capas al hacer clic Show hover bounds from Layers Mostrar límites al pasar el puntero desde Capas - Saved Camera Raw settings to {file} Ajustes de Camera Raw guardados en {file} + Saved RAW Develop settings to {file} Ajustes de Revelado RAW guardados en {file} Save the settings to each raw's sidecar without opening it Guardar los ajustes en el archivo sidecar de cada raw sin abrirlo No settings saved: these raws can't keep a sidecar here No se guardó nada: estos raw no pueden tener un archivo sidecar aquí Some settings could not be saved; the raws stay open No se pudieron guardar algunos ajustes; los raw siguen abiertos @@ -4527,3 +4526,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Ajustar tamaño de lienzo automáticamente Keep Relative Position During Layer Reordering Mantener la posición relativa al reordenar capas Shrinkwrap Canvas on Save Reducir el lienzo al contenido al guardar + Move Toolbar to the Right Mover la barra de herramientas a la derecha + Move Toolbar to the Left Mover la barra de herramientas a la izquierda diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index eb99627d4f..7b3073240e 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -186,8 +186,8 @@ Trap… Trappaus… # Layer - Layer via Copy Taso kopioimalla - Layer via Cut Taso leikkaamalla + Layer Via Copy Taso kopioimalla + Layer Via Cut Taso leikkaamalla Duplicate Layer… Monista taso… Duplicate… Monista… Delete Poista @@ -351,7 +351,7 @@ Last Filter Viimeisin suodatin Filter Gallery… Suodatingalleria… Liquify… Nesteytä… - Camera Raw Filter… Camera Raw -suodatin… + RAW Develop Filter… RAW-kehitys -suodatin… Adaptive Wide Angle… Mukautuva laajakulma… Lens Correction… Objektiivin korjaus… Vanishing Point… Pakopiste… @@ -876,7 +876,7 @@ Working Black Plate Työ-mustalevy Working Gray Plate Harmaa työlevy -# Camera Raw and lens dialogs +# RAW Develop and lens dialogs Basic Perusasetukset Detail Yksityiskohdat HSL/Grayscale HSL/harmaasävy @@ -906,8 +906,8 @@ Luminance Smoothness Luminanssin tasaisuus Vignetting Vinjetointi White Balance: As Shot Valkotasapaino: kuvauksen mukainen - Camera Raw… Camera Raw… - Camera Raw isn't open Camera Raw ei ole auki + RAW Defaults… RAW-oletukset… + RAW Develop isn't open RAW-kehitys ei ole auki Dehaze Usvanpoisto Texture Tekstuuri Focal Length Polttoväli @@ -1178,8 +1178,6 @@ Roman Hanging Punctuation Latinalainen riippuva välimerkitys Avoid Widows/Orphans Vältä leski- ja orporivejä Compose Sommittele - Adobe Single-line Composer Adobe yksirivinen asettelija - Adobe Every-line Composer Adobe kaikkien rivien asettelija Justification Tasaus Word Spacing Sanaväli Letter Spacing Merkkiväli @@ -1761,8 +1759,8 @@ Load Settings… Lataa asetukset… Save these settings as a Camera Raw .xmp file Tallenna nämä asetukset Camera Raw .xmp -tiedostona Load settings from a Camera Raw .xmp file Lataa asetukset Camera Raw .xmp -tiedostosta - Loaded Camera Raw settings from {file} Camera Raw -asetukset ladattu tiedostosta {file} - Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw -asetukset ladattu tiedostosta {file} ({n} tukematonta) + Loaded RAW Develop settings from {file} RAW-kehitys -asetukset ladattu tiedostosta {file} + Loaded RAW Develop settings from {file} ({n} not supported) RAW-kehitys -asetukset ladattu tiedostosta {file} ({n} tukematonta) After (X) Jälkeen (X) Original Alkuperäinen Current Nykyinen @@ -2349,7 +2347,7 @@ CPU (no GPU acceleration) CPU (ei GPU-kiihdytystä) Cache levels Välimuistitasot Cache tile size Välimuistin laatan koko - Camera Raw Defaults Camera Raw -oletukset + RAW Defaults RAW-oletukset Canvas border Kankaan reunus Show canvas dots Näytä kankaan pisteet Clip thumbnails to layer bounds Rajaa pikkukuvat tason rajoihin @@ -2441,7 +2439,6 @@ Never Ei koskaan Normal tip Normaali kärki Open as smart object Avaa älykkäänä objektina - Open in camera raw Avaa Camera Raw'ssa Open documents as tabs Avaa asiakirjat välilehtinä OpenGL OpenGL Orange Oranssi @@ -2582,9 +2579,9 @@ Tone Histogram Sävyhistogrammi Show Selected Region Näytä valittu alue cameraRaw Light Valo -# Camera Raw: contextual controls and window title - Camera Raw Filter ({layer}) Camera Raw -suodatin ({layer}) - Camera Raw ({name}) Camera Raw ({name}) +# RAW Develop: contextual controls and window title + RAW Develop Filter ({layer}) RAW-kehitys -suodatin ({layer}) + RAW Develop ({name}) RAW-kehitys ({name}) Aqua Turkoosi cameraRaw Amount Määrä cameraRaw Blacks Mustat @@ -3389,7 +3386,7 @@ curves Smooth Tasoita {name} was changed by another app after it was opened or saved here. Toinen ohjelma on muuttanut tiedostoa {name} sen jälkeen, kun se avattiin tai tallennettiin täällä. Replace it with this document, or cancel and use File › Save As to keep both. Korvaa se tällä asiakirjalla, tai peruuta ja käytä komentoa Tiedosto › Tallenna nimellä, jos haluat säilyttää molemmat. -# Dynamic UI labels (fourth pass): filter and adjustment parameters, Camera Raw panels, +# Dynamic UI labels (fourth pass): filter and adjustment parameters, RAW Develop panels, # lighting, History/Layers/paths/channels menus, metadata, System Info, status templates and # dialog text that other catalogs already carry. Written from the meaning of the English labels # in the ordinary Russian graphics-editor vocabulary; no proprietary resource consulted. @@ -3415,13 +3412,11 @@ curves Smooth Tasoita Adjustment Layers Säätötasot Adjustment Properties Säädön ominaisuudet Adjustment layers have nothing to transform Säätötasoilla ei ole mitään muunnettavaa - Adobe PDF Presets… Adobe PDF -esiasetukset… Adobe-rgb-compat Adobe RGB -yhteensopiva Adwaita (Dark) Adwaita (tumma) Adwaita (Light) Adwaita (vaalea) After Jälkeen Airbrush: keeps painting while the pointer rests. Ilmasivellin: maalaa edelleen, kun osoitin on paikallaan. - All shortcuts reset to Photoshop defaults. Kaikki pikanäppäimet palautettu Photoshopin oletuksiin. Altitude Korkeus Ambience Ympäristövalo Ambient Ympäristö @@ -3506,8 +3501,8 @@ curves Smooth Tasoita Brush Type Siveltimen tyyppi Burlap Juuttikangas Calculations Laskutoimitukset - Camera Raw Camera Raw - Camera Raw Filter Camera Raw -suodatin + RAW Develop RAW-kehitys + RAW Develop Filter RAW-kehitys -suodatin Cancel transform Peruuta muunnos Candle Light Kynttilänvalo Canvas Size Kankaan koko @@ -3654,7 +3649,6 @@ curves Smooth Tasoita Deep Yellow Syvä keltainen Default Foreground and Background Colors Oletusarvoiset edusta- ja taustavärit Default Leaves Oletuslehdet - Default Photoshop Size Photoshopin oletuskoko Defaults Oletukset Define Brush Preset Määritä siveltimen esiasetus Define Custom Shape Määritä mukautettu muoto @@ -4494,7 +4488,7 @@ curves Smooth Tasoita The file could not be saved. Tiedostoa ei voitu tallentaa. Thickness Paksuus This Layer: Tämä taso: - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Tämä älykäs objekti on rasteroitava ennen jatkamista. Sen sisältöä ei voi enää muokata. Rasteroidaanko älykäs objekti? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Tämä älykäs objekti on rasteroitava ennen jatkamista. Sen sisältöä ei voi enää muokata. Rasteroidaanko älykäs objekti? This adjustment ({key}) is kept as imported and can't be edited yet. Tämä säätö ({key}) säilytetään tuotuna, eikä sitä voi vielä muokata. This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Tämä täyttötaso on rasteroitava ennen jatkamista. Sen täyttösisältöä ei voi enää muokata. Rasteroidaanko taso? This layer must be rasterized before proceeding. Tämä taso on rasteroitava ennen jatkamista. @@ -4706,6 +4700,7 @@ shape Appearance Ulkoasu Grayscale Ramp Harmaasävyliukuma Current Colors Nykyiset värit Make Ramp Web Safe Rajoita liukuma verkkoturvallisiin väreihin + Scroll All Windows Vieritä kaikkia ikkunoita # Art History Brush (#213). Art History Brush Tool Taidehistoriasivellintyökalu Tight Short Tiivis lyhyt @@ -4754,9 +4749,9 @@ shape Appearance Ulkoasu @plural {n} document|{n} documents {n} asiakirja|{n} asiakirjaa @plural {n} pixel|{n} pixels {n} pikseli|{n} pikseliä cameraRaw Before (Y) Ennen (Y) -cameraRaw Camera Raw ({name}) Camera Raw ({name}) -cameraRaw Camera Raw Filter ({layer}) Camera Raw -suodatin ({layer}) -cameraRaw Camera Raw isn't open Camera Raw ei ole auki +cameraRaw RAW Develop ({name}) RAW-kehitys ({name}) +cameraRaw RAW Develop Filter ({layer}) RAW-kehitys -suodatin ({layer}) +cameraRaw RAW Develop isn't open RAW-kehitys ei ole auki cameraRaw Cancel Peruuta cameraRaw Canceled opening {name} Tiedoston {name} avaaminen peruutettu cameraRaw Canceled {label} Peruutettu: {label} @@ -4768,7 +4763,7 @@ cameraRaw Highlight Clipping Warning (O) Korostusten leikkautumisvaroitus (O) cameraRaw Highlight Priority Korostusten prioriteetti cameraRaw Load Settings… Lataa asetukset… cameraRaw Load settings from a Camera Raw .xmp file Lataa asetukset Camera Raw .xmp -tiedostosta -cameraRaw Loaded Camera Raw settings from {file} Camera Raw -asetukset ladattu tiedostosta {file} +cameraRaw Loaded RAW Develop settings from {file} RAW-kehitys -asetukset ladattu tiedostosta {file} cameraRaw Noise Reduction Kohinan vaimennus cameraRaw OK OK cameraRaw Open Avaa @@ -4814,6 +4809,7 @@ cameraRaw White Balance: As Shot Valkotasapaino: kuvauksen mukainen Pick a different document for each channel. Valitse jokaiselle kanavalle eri asiakirja. A picked document is no longer open. Yksi valituista asiakirjoista ei ole enää auki. A picked document is no longer a grayscale document of the same size. Yksi valituista asiakirjoista ei ole enää samankokoinen harmaasävyasiakirja. + Netscape Gray Netscape-harmaa # Move tool options bar (#11381) Align top edges Tasaa yläreunat Align vertical centers Tasaa pystykeskikohdat @@ -4830,3 +4826,8 @@ cameraRaw White Balance: As Shot Valkotasapaino: kuvauksen mukainen Auto-size Canvas Muuta kankaan kokoa automaattisesti Keep Relative Position During Layer Reordering Säilytä suhteellinen sijainti tasojen järjestystä muutettaessa Shrinkwrap Canvas on Save Pienennä kangas sisältöön tallennettaessa + Move Toolbar to the Right Siirrä työkalupalkki oikealle + Move Toolbar to the Left Siirrä työkalupalkki vasemmalle + +# RAW Develop feature labels + Saved RAW Develop settings to {file} RAW-kehityksen asetukset tallennettu tiedostoon {file} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index c0a008b3e4..f66fdea173 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -38,7 +38,7 @@ # Labels added on main after this catalog (depth labels, Wayland drop, profiles, rendering mode) -# Camera Raw scopes and the Patch tool +# RAW Develop scopes and the Patch tool # Warp grid presets (#388) @@ -326,7 +326,7 @@ Plugins… Extensions… Type… Texte… Enhanced Controls… Commandes avancées… - Camera Raw… Camera Raw… + RAW Defaults… Valeurs par défaut RAW… Raw Defaults… Valeurs Raw par défaut… Integrations… Intégrations… AI Integrations… Intégrations d'IA… @@ -410,8 +410,8 @@ Artboard… Plan de travail… Artboard from Group… Plan de travail d'après un groupe… Artboard from Layers… Plan de travail d'après des calques… - Layer via Copy Calque par copie - Layer via Cut Calque par coupe + Layer Via Copy Calque par copie + Layer Via Cut Calque par coupe Layer From Background… Calque d'après l'arrière-plan… Layer from Background… Calque d'après l'arrière-plan… Background From Layer Arrière-plan d'après le calque @@ -645,7 +645,7 @@ Last Filter Dernier filtre Filter Gallery… Galerie de filtres… Adaptive Wide Angle… Grand angle adaptatif… - Camera Raw Filter… Filtre Camera Raw… + RAW Develop Filter… Filtre Développement RAW… Liquify… Liquéfier… Vanishing Point… Point de fuite… Blur Flou @@ -999,8 +999,8 @@ Load Settings… Charger les paramètres… Save these settings as a Camera Raw .xmp file Enregistrer ces paramètres dans un fichier .xmp Camera Raw Load settings from a Camera Raw .xmp file Charger les paramètres d’un fichier .xmp Camera Raw - Loaded Camera Raw settings from {file} Paramètres Camera Raw chargés depuis {file} - Loaded Camera Raw settings from {file} ({n} not supported) Paramètres Camera Raw chargés depuis {file} ({n} non pris en charge) + Loaded RAW Develop settings from {file} Paramètres Développement RAW chargés depuis {file} + Loaded RAW Develop settings from {file} ({n} not supported) Paramètres Développement RAW chargés depuis {file} ({n} non pris en charge) Begin recording Démarrer l'enregistrement Bend: Courbure : Bicubic Bicubique @@ -1028,7 +1028,7 @@ Brush Reconstruct Options Options du pinceau de reconstruction Brush Tool Options Options de l'outil Pinceau Cache Level: Niveau de cache : - Camera Raw isn't open Camera Raw n'est pas ouvert + RAW Develop isn't open Développement RAW n'est pas ouvert Cancel Annuler Cancel (Esc) Annuler (Échap) Manage submitted jobs in the system print queue Gérer les tâches soumises dans la file d’impression du système @@ -1990,7 +1990,7 @@ Brush preview color Couleur de l'aperçu du pinceau Cache levels Niveaux de cache Cache tile size Taille des tuiles du cache - Camera Raw Defaults Valeurs par défaut de Camera Raw + RAW Defaults Valeurs par défaut RAW Canvas border Bordure du canevas Show canvas dots Afficher les points du canevas Clip thumbnails to layer bounds Rogner les vignettes aux limites du calque @@ -2077,7 +2077,6 @@ Never Jamais Normal tip Pointe normale Open as smart object Ouvrir en tant qu'objet intelligent - Open in camera raw Ouvrir dans Camera Raw Open documents as tabs Ouvrir les documents dans des onglets Overscroll Défilement au-delà des bords Performance Performances @@ -2481,8 +2480,6 @@ Roman Hanging Punctuation Ponctuation latine hors justification Avoid Widows/Orphans Éviter les veuves et orphelines Compose Composition - Adobe Single-line Composer Composeur ligne par ligne Adobe - Adobe Every-line Composer Composeur multiligne Adobe Justification Justification Word Spacing Espacement des mots Letter Spacing Espacement des lettres @@ -2737,7 +2734,6 @@ Intersect with Intersection avec Capture Comp Capturer la composition No Layer Comps Aucune composition de calques - Adobe PDF Presets… Préréglages Adobe PDF… 3D… 3D… Technology Previews… Aperçus technologiques… Background from Layer Arrière-plan d'après le calque @@ -2828,8 +2824,8 @@ Tone Histogram Histogramme des tons Show Selected Region Afficher la zone sélectionnée cameraRaw Light Lumière - Camera Raw Filter ({layer}) Filtre Camera Raw ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) Filtre Développement RAW ({layer}) + RAW Develop ({name}) Développement RAW ({name}) cameraRaw Lights Tons clairs cameraRaw Darks Tons sombres cameraRaw Blacks Noirs @@ -3512,7 +3508,6 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Adwaita (Dark) Adwaita (sombre) Adwaita (Light) Adwaita (clair) After Après - All shortcuts reset to Photoshop defaults. Tous les raccourcis ont été réinitialisés aux valeurs par défaut de Photoshop. Ambience Ambiance Ambient Ambiante Amplitude Max Amplitude max. @@ -3588,8 +3583,8 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Brush Type Type de pinceau Burlap Toile de jute Calculations Calculs - Camera Raw Camera Raw - Camera Raw Filter Filtre Camera Raw + RAW Develop Développement RAW + RAW Develop Filter Filtre Développement RAW Cancel transform Annuler la transformation Candle Light Bougie Canvas Size Taille du canevas @@ -3698,7 +3693,6 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Deep Yellow Jaune profond Default Foreground and Background Colors Couleurs par défaut du premier plan et de l'arrière-plan Default Leaves Feuilles par défaut - Default Photoshop Size Taille Photoshop par défaut Defaults Valeurs par défaut Define Brush Preset Définir un préréglage de pinceau Define Custom Shape Définir une forme personnalisée @@ -4333,7 +4327,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded The file could not be saved. Impossible d'enregistrer le fichier. Thickness Épaisseur This Layer: Ce calque : - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Cet objet intelligent doit être rastérisé pour continuer. Son contenu ne sera plus modifiable. Rastériser l'objet intelligent ? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Cet objet intelligent doit être rastérisé pour continuer. Son contenu ne sera plus modifiable. Rastériser l'objet intelligent ? This adjustment ({key}) is kept as imported and can't be edited yet. Cet ajustement ({key}) est conservé tel qu'il a été importé et ne peut pas encore être modifié. This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Ce calque de remplissage doit être rastérisé pour continuer. Son contenu de remplissage ne sera plus modifiable. Rastériser le calque ? This layer must be rasterized before proceeding. Ce calque doit être rastérisé pour continuer. @@ -4543,8 +4537,10 @@ shape Appearance Apparence Grayscale Ramp Barre de niveaux de gris Current Colors Couleurs actuelles Make Ramp Web Safe Limiter la barre aux couleurs Web + Scroll All Windows Faire défiler toutes les fenêtres The path was kept as the Work Path Le tracé a été conservé comme tracé de travail The path was discarded Le tracé a été supprimé +# Art History Brush (#213). Art History Brush Tool Outil Pinceau d'historique artistique Tight Short Serré court Tight Medium Serré moyen @@ -4629,6 +4625,7 @@ shape Appearance Apparence Pick a different document for each channel. Choisissez un document différent pour chaque canal. A picked document is no longer open. Un des documents choisis n'est plus ouvert. A picked document is no longer a grayscale document of the same size. Un des documents choisis n'est plus un document en niveaux de gris de même taille. + Netscape Gray Gris Netscape # Move tool options bar (#11381) Align top edges Aligner les bords supérieurs Align vertical centers Aligner les centres verticaux @@ -4638,7 +4635,7 @@ shape Appearance Apparence Show layer bounds on hover Afficher les limites du calque au survol Expand layer group on click Développer le groupe de calques au clic Show hover bounds from Layers Afficher les limites au survol depuis Calques - Saved Camera Raw settings to {file} Réglages Camera Raw enregistrés dans {file} + Saved RAW Develop settings to {file} Réglages Développement RAW enregistrés dans {file} Save the settings to each raw's sidecar without opening it Enregistrer les réglages dans le fichier annexe de chaque raw sans l’ouvrir No settings saved: these raws can't keep a sidecar here Rien n’a été enregistré : ces raw ne peuvent pas avoir de fichier annexe ici Some settings could not be saved; the raws stay open Certains réglages n’ont pas pu être enregistrés ; les raw restent ouverts @@ -4650,3 +4647,5 @@ shape Appearance Apparence Auto-size Canvas Redimensionner le canevas automatiquement Keep Relative Position During Layer Reordering Conserver la position relative lors de la réorganisation des calques Shrinkwrap Canvas on Save Réduire le canevas au contenu à l'enregistrement + Move Toolbar to the Right Déplacer la barre d'outils à droite + Move Toolbar to the Left Déplacer la barre d'outils à gauche diff --git a/crates/ui-egui/src/i18n/he.tsv b/crates/ui-egui/src/i18n/he.tsv index d38b62ed3a..d6bb149798 100644 --- a/crates/ui-egui/src/i18n/he.tsv +++ b/crates/ui-egui/src/i18n/he.tsv @@ -224,7 +224,7 @@ Plug-ins… תוספים… Type… טקסט… Enhanced Controls… פקדים משופרים… - Camera Raw… Camera Raw… + RAW Defaults… ברירות מחדל RAW… Raw Defaults… ברירות מחדל ל-Raw… Integrations… שילובים… AI Integrations… שילובי בינה מלאכותית… @@ -311,8 +311,8 @@ Artboard… לוח ציור… Artboard from Group… לוח ציור מקבוצה… Artboard from Layers… לוח ציור משכבות… - Layer via Copy שכבה דרך העתקה - Layer via Cut שכבה דרך גזירה + Layer Via Copy שכבה דרך העתקה + Layer Via Cut שכבה דרך גזירה Layer From Background… שכבה מרקע… Layer from Background… שכבה מרקע… Background from Layer רקע משכבה @@ -554,7 +554,7 @@ Last Filter המסנן האחרון Filter Gallery… גלריית מסננים… Adaptive Wide Angle… זווית רחבה אדפטיבית… - Camera Raw Filter… מסנן Camera Raw… + RAW Develop Filter… מסנן פיתוח RAW… Liquify… נזילות… Vanishing Point… נקודת היעלמות… Blur טשטוש @@ -902,8 +902,8 @@ Load Settings… טען הגדרות… Save these settings as a Camera Raw .xmp file שמור הגדרות אלה כקובץ ‎.xmp של Camera Raw Load settings from a Camera Raw .xmp file טען הגדרות מקובץ ‎.xmp של Camera Raw - Loaded Camera Raw settings from {file} נטענו הגדרות Camera Raw מתוך {file} - Loaded Camera Raw settings from {file} ({n} not supported) נטענו הגדרות Camera Raw מתוך {file} ({n} לא נתמכות) + Loaded RAW Develop settings from {file} נטענו הגדרות פיתוח RAW מתוך {file} + Loaded RAW Develop settings from {file} ({n} not supported) נטענו הגדרות פיתוח RAW מתוך {file} ({n} לא נתמכות) Begin recording התחל הקלטה Bend: כיפוף: Bicubic דו-מעוקב (Bicubic) @@ -931,7 +931,7 @@ Brush Reconstruct Options אפשרויות שחזור מברשת Brush Tool Options אפשרויות כלי מברשת Cache Level: רמת מטמון: - Camera Raw isn't open Camera Raw אינו פתוח + RAW Develop isn't open פיתוח RAW אינו פתוח Cancel ביטול Cancel (Esc) ביטול (Esc) Manage submitted jobs in the system print queue נהל עבודות שנשלחו בתור ההדפסה של המערכת @@ -1902,7 +1902,7 @@ Brush preview color צבע תצוגה מקדימה של מברשת Cache levels רמות מטמון Cache tile size גודל אריח מטמון - Camera Raw Defaults ברירות מחדל של Camera Raw + RAW Defaults ברירות מחדל RAW Canvas border גבול קנבס Show canvas dots הצג נקודות קנבס Clip thumbnails to layer bounds גזור תמונות ממוזערות לגבולות השכבה @@ -1984,7 +1984,6 @@ Never לעולם לא Normal tip קצה רגיל Open as smart object פתח כאובייקט חכם - Open in camera raw פתח ב-Camera Raw Open documents as tabs פתח מסמכים כלשוניות Overscroll גלילת יתר Performance ביצועים @@ -2345,8 +2344,8 @@ Tone Histogram היסטוגרמת גוון Show Selected Region הצג אזור נבחר cameraRaw Light אור - Camera Raw Filter ({layer}) מסנן Camera Raw ‏({layer}) - Camera Raw ({name}) Camera Raw ‏({name}) + RAW Develop Filter ({layer}) מסנן פיתוח RAW ‏({layer}) + RAW Develop ({name}) פיתוח RAW ‏({name}) cameraRaw Lights בהירים cameraRaw Darks כהים cameraRaw Red אדום @@ -2943,8 +2942,6 @@ curves Smooth החלק Roman Hanging Punctuation פיסוק תלוי רומי Avoid Widows/Orphans הימנע משורות יתומות/אלמנות Compose הרכב - Adobe Single-line Composer מרכיב שורה בודדת של Adobe - Adobe Every-line Composer מרכיב כל השורות של Adobe Word Spacing ריווח מילים Letter Spacing ריווח אותיות Glyph Scaling שינוי קנה מידה של גליפים @@ -3140,7 +3137,6 @@ curves Smooth החלק Intersect with חתוך עם Capture Comp לכוד קומפ No Layer Comps אין קומפים של שכבות - Adobe PDF Presets… ערכות PDF של Adobe… 3D… 3D… Technology Previews… תצוגות מקדימות של טכנולוגיה… Add a mask (from the selection; ⌥ inverts) הוסף מסכה (מהבחירה; ⌥ הופך) @@ -3757,8 +3753,8 @@ layerLabel No Color בלי צבע Border גבול Box Blur טשטוש קופסה Calculations חישובים - Camera Raw Camera Raw - Camera Raw Filter מסנן Camera Raw + RAW Develop פיתוח RAW + RAW Develop Filter מסנן פיתוח RAW Channel1 ערוץ1 Channel2 ערוץ2 Channel3 ערוץ3 @@ -4018,7 +4014,7 @@ layerLabel No Color בלי צבע Scroll menu down גלול תפריט למטה This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? שכבת הטקסט הזו חייבת להיות מרוסטרת לפני ההמשך. הטקסט שלה לא יהיה עוד עריך. לרסטר את הטקסט? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? שכבת הצורה הזו חייבת להיות מרוסטרת לפני ההמשך. היא לא תהיה עוד עריכה כצורה. לרסטר את הצורה? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? האובייקט החכם הזה חייב להיות מרוסטר לפני ההמשך. התוכן שלו לא יהיה עוד עריך. לרסטר את האובייקט החכם? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? האובייקט החכם הזה חייב להיות מרוסטר לפני ההמשך. התוכן שלו לא יהיה עוד עריך. לרסטר את האובייקט החכם? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? שכבת המילוי הזו חייבת להיות מרוסטרת לפני ההמשך. תוכן המילוי שלה לא יהיה עוד עריך. לרסטר את השכבה? This layer must be rasterized before proceeding. השכבה הזו חייבת להיות מרוסטרת לפני ההמשך. Color Picker (Background Color) בוחר צבעים (צבע רקע) @@ -4572,3 +4568,8 @@ navigator Zoom תקריב @plural {n} action file loaded|{n} action files loaded נטען {n} קובץ פעולות|נטענו {n} קובצי פעולות @plural {n} file could not be loaded: {errors}|{n} files could not be loaded: {errors} לא ניתן היה לטעון {n} קובץ: {errors}|לא ניתן היה לטעון {n} קבצים: {errors} @plural {what}: {n} Image Assets output failed|{what}: {n} Image Assets outputs failed {what}: {n} פלט נכסי תמונה נכשל|{what}: {n} פלטי נכסי תמונה נכשלו + Move Toolbar to the Right העבר את סרגל הכלים ימינה + Move Toolbar to the Left העבר את סרגל הכלים שמאלה + +# RAW Develop feature labels + Saved RAW Develop settings to {file} הגדרות פיתוח RAW נשמרו ב־{file} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2e6854129a..897c6c3440 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -40,7 +40,7 @@ # Tool and Scope strings -# Camera Raw +# RAW Develop # Coverage-test keys (English until translated) @@ -357,8 +357,8 @@ Impressionist प्रभाववादी Aligned संरेखित Fit in View दृश्य में फ़िट करें - Camera Raw Camera Raw - Camera Raw… Camera Raw… + RAW Develop RAW डेवलप + RAW Defaults… RAW डिफ़ॉल्ट… cameraRaw Amount मात्रा Amount मात्रा cameraRaw Aqua एक्वा @@ -373,11 +373,11 @@ cameraRaw Blending मिश्रण Blending मिश्रण cameraRaw Blue नीला Blue नीला -cameraRaw Camera Raw ({name}) Camera Raw ({name}) -cameraRaw Camera Raw Filter ({layer}) Camera Raw फ़िल्टर ({layer}) - Camera Raw Filter ({layer}) Camera Raw फ़िल्टर ({layer}) -cameraRaw Camera Raw isn't open Camera Raw खुला नहीं है - Camera Raw isn't open Camera Raw खुला नहीं है +cameraRaw RAW Develop ({name}) RAW डेवलप ({name}) +cameraRaw RAW Develop Filter ({layer}) RAW डेवलप फ़िल्टर ({layer}) + RAW Develop Filter ({layer}) RAW डेवलप फ़िल्टर ({layer}) +cameraRaw RAW Develop isn't open RAW डेवलप खुला नहीं है + RAW Develop isn't open RAW डेवलप खुला नहीं है cameraRaw Cancel रद्द करें cameraRaw Canceled opening {name} {name} खोलना रद्द किया गया Canceled opening {name} {name} खोलना रद्द किया गया @@ -436,8 +436,8 @@ cameraRaw Load Settings… सेटिंग्स लोड करें… Load Settings… सेटिंग्स लोड करें… cameraRaw Load settings from a Camera Raw .xmp file Camera Raw .xmp फ़ाइल से सेटिंग्स लोड करें Load settings from a Camera Raw .xmp file Camera Raw .xmp फ़ाइल से सेटिंग्स लोड करें -cameraRaw Loaded Camera Raw settings from {file} {file} से Camera Raw सेटिंग्स लोड की गईं - Loaded Camera Raw settings from {file} {file} से Camera Raw सेटिंग्स लोड की गईं +cameraRaw Loaded RAW Develop settings from {file} {file} से RAW डेवलप सेटिंग्स लोड की गईं + Loaded RAW Develop settings from {file} {file} से RAW डेवलप सेटिंग्स लोड की गईं cameraRaw Luminance लुमिनेंस Luminance लुमिनेंस cameraRaw Luminance Detail लुमिनेंस डिटेल @@ -559,6 +559,7 @@ cameraRaw Yellow पीला Layer deleted, but confirmation preference could not be saved: {error} लेयर हटा दी गई, लेकिन पुष्टि की प्राथमिकता सहेजी नहीं जा सकी: {error} The path was kept as the Work Path पथ को कार्य पथ के रूप में रखा गया The path was discarded पथ हटा दिया गया + Scroll All Windows सभी विंडो स्क्रॉल करें Art History Brush आर्ट हिस्ट्री ब्रश Style शैली Area क्षेत्र @@ -675,6 +676,7 @@ cameraRaw Yellow पीला Pick a different document for each channel. हर चैनल के लिए अलग डॉक्यूमेंट चुनें। A picked document is no longer open. चुना गया एक डॉक्यूमेंट अब खुला नहीं है। A picked document is no longer a grayscale document of the same size. चुना गया एक डॉक्यूमेंट अब उसी आकार का ग्रेस्केल डॉक्यूमेंट नहीं है। + Netscape Gray Netscape धूसर # Move tool options bar (#11381) Align top edges ऊपरी किनारे संरेखित करें Align vertical centers ऊर्ध्वाधर केंद्र संरेखित करें @@ -691,3 +693,12 @@ cameraRaw Yellow पीला Auto-size Canvas कैनवास का आकार स्वचालित रूप से बदलें Keep Relative Position During Layer Reordering लेयर्स का क्रम बदलते समय सापेक्ष स्थिति बनाए रखें Shrinkwrap Canvas on Save सहेजते समय कैनवास को सामग्री के अनुसार छोटा करें + Move Toolbar to the Right टूलबार को दाएँ ले जाएँ + Move Toolbar to the Left टूलबार को बाएँ ले जाएँ + RAW Defaults RAW डिफ़ॉल्ट + +# RAW Develop feature labels + Saved RAW Develop settings to {file} RAW डेवलप सेटिंग्स {file} में सहेजी गईं + RAW Develop Filter RAW डेवलप फ़िल्टर + RAW Develop Filter… RAW डेवलप फ़िल्टर… + Loaded RAW Develop settings from {file} ({n} not supported) {file} से RAW डेवलप सेटिंग्स लोड की गईं ({n} समर्थित नहीं) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index ced7e54f43..cfcce4a24f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -34,7 +34,7 @@ # Adjustments and filters -# Camera Raw and camera data +# RAW Develop and camera data # Dialogs, preferences and file formats @@ -409,8 +409,8 @@ Layer Content Options… Rétegtartalom beállításai… Layer from Background… Réteg a háttérből… Layer Style Rétegstílus - Layer via Copy Réteg másolással - Layer via Cut Réteg kivágással + Layer Via Copy Réteg másolással + Layer Via Cut Réteg kivágással Layer… Réteg… Left Edges Bal szélek Link Layer Mask Rétegmaszk összekapcsolása @@ -544,7 +544,7 @@ Brush Settings Ecsetbeállítások Brushes Ecsetek brushes ecsetek - Camera Raw Filter… Camera Raw szűrő… + RAW Develop Filter… RAW-előhívás szűrő… Canvas Guides Vászon-segédvonalak Cascade Lépcsőzetes Change Panel Group Panelcsoport váltása @@ -2573,11 +2573,11 @@ navigator Zoom Nagyítás mértéke Balance Egyensúly Before (Y) Előtte (Y) Blending Keverés - Camera Raw Camera Raw - Camera Raw ({name}) Camera Raw ({name}) - Camera Raw Filter Camera Raw szűrő - Camera Raw Filter ({layer}) Camera Raw szűrő ({layer}) - Camera Raw isn't open A Camera Raw nincs megnyitva + RAW Develop RAW-előhívás + RAW Develop ({name}) RAW-előhívás ({name}) + RAW Develop Filter RAW-előhívás szűrő + RAW Develop Filter ({layer}) RAW-előhívás szűrő ({layer}) + RAW Develop isn't open A RAW-előhívás nincs megnyitva Canceled opening {name} Megnyitás megszakítva: {name} Damaged Photoshop document Sérült Photoshop-dokumentum The document “{name}” may be damaged. A(z) „{name}” dokumentum sérült lehet. @@ -2630,7 +2630,6 @@ navigator Zoom Nagyítás mértéke Noise Luminance Zajcsökkentés: luminancia Noise Luminance Detail Zajcsökkentés: luminancia-részletesség Noise Reduction Zajcsökkentés - Open in camera raw Megnyitás a Camera Raw-ban Paint Overlay Ráfestés Previous Előző Purple Lila @@ -3090,7 +3089,7 @@ cameraRaw Yellow Sárga This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? A folytatáshoz a kitöltőréteget raszterizálni kell. A kitöltés tartalma ezután nem lesz szerkeszthető. Raszterizálod a réteget? This layer must be rasterized before proceeding. A folytatáshoz a réteget raszterizálni kell. This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? A folytatáshoz az alakzatréteget raszterizálni kell. Ezután alakzatként nem lesz szerkeszthető. Raszterizálod az alakzatot? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? A folytatáshoz az intelligens objektumot raszterizálni kell. A tartalma ezután nem lesz szerkeszthető. Raszterizálod az intelligens objektumot? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? A folytatáshoz az intelligens objektumot raszterizálni kell. A tartalma ezután nem lesz szerkeszthető. Raszterizálod az intelligens objektumot? This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? A folytatáshoz a szövegréteget raszterizálni kell. A szöveg ezután nem lesz szerkeszthető. Raszterizálod a szöveget? TIFF Options TIFF-beállítások Top: Felső: @@ -3188,8 +3187,8 @@ cameraRaw Yellow Sárga Cache levels Gyorsítótár-szintek Cache tile size Gyorsítótár csempemérete Camera Data Fényképezőgép adatai - Camera Raw Defaults Camera Raw-alapértékek - Camera Raw… Camera Raw… + RAW Defaults RAW-alapértékek + RAW Defaults… RAW-alapértékek… Cancel opening Megnyitás megszakítása Canvas border Vászonszegély Canvas extension color: Vászonbővítés színe: @@ -3779,9 +3778,6 @@ cameraRaw Yellow Sárga Add to selection (⇧) Hozzáadás a kijelöléshez (⇧) Adds grain to the soft edges of the brush tip. Szemcsézettséget ad az ecsethegy lágy széleihez. Adjustment Layers Korrekciós rétegek - Adobe Every-line Composer Adobe többsoros szedőmotor - Adobe PDF Presets… Adobe PDF-előbeállítások… - Adobe Single-line Composer Adobe egysoros szedőmotor Advanced Controls Speciális vezérlők After (X) Utána (X) Airbrush: keeps painting while the pointer rests. Festékszóró: a festés akkor is folytatódik, amikor a mutató áll. @@ -4193,8 +4189,8 @@ cameraRaw Yellow Sárga Load Settings… Beállítások betöltése… Save these settings as a Camera Raw .xmp file A beállítások mentése Camera Raw .xmp-fájlként Load settings from a Camera Raw .xmp file Beállítások betöltése Camera Raw .xmp-fájlból - Loaded Camera Raw settings from {file} Camera Raw-beállítások betöltve innen: {file} - Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw-beállítások betöltve innen: {file} ({n} nem támogatott) + Loaded RAW Develop settings from {file} RAW-előhívás-beállítások betöltve innen: {file} + Loaded RAW Develop settings from {file} ({n} not supported) RAW-előhívás-beállítások betöltve innen: {file} ({n} nem támogatott) Auto Add/Delete Automatikus hozzáadás/törlés Don't also tick Mirror Image in Print Settings…: the two flips cancel out. A nyomtatási beállításokban ne jelöld be a tükrözést is: a két tükrözés kioltja egymást. Print Settings… Nyomtatási beállítások… @@ -4426,8 +4422,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Szürkeárnyalatos sáv Current Colors Aktuális színek Make Ramp Web Safe Sáv korlátozása webes színekre + Scroll All Windows Összes ablak görgetése The path was kept as the Work Path Az útvonal munkaútvonalként megmaradt The path was discarded Az útvonal el lett vetve +# Art History Brush (#213). Art History Brush Tool Művészi előzményecset eszköz Tight Short Szoros, rövid Tight Medium Szoros, közepes @@ -4513,6 +4511,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Minden csatornához másik dokumentumot válasszon. A picked document is no longer open. Az egyik kiválasztott dokumentum már nincs megnyitva. A picked document is no longer a grayscale document of the same size. Az egyik kiválasztott dokumentum már nem azonos méretű szürkeárnyalatos dokumentum. + Netscape Gray Netscape-szürke # Move tool options bar (#11381) Align top edges Felső szélek igazítása Align vertical centers Függőleges középpontok igazítása @@ -4522,7 +4521,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Réteghatárok megjelenítése rámutatáskor Expand layer group on click Rétegcsoport kibontása kattintásra Show hover bounds from Layers Határok megjelenítése a Rétegek panelről rámutatáskor - Saved Camera Raw settings to {file} Camera Raw-beállítások mentve ide: {file} + Saved RAW Develop settings to {file} RAW-előhívás-beállítások mentve ide: {file} Save the settings to each raw's sidecar without opening it A beállítások mentése minden raw kísérőfájljába megnyitás nélkül No settings saved: these raws can't keep a sidecar here Nincs mentve semmi: ezek a raw fájlok itt nem kaphatnak kísérőfájlt Some settings could not be saved; the raws stay open Néhány beállítást nem sikerült menteni; a raw fájlok nyitva maradnak @@ -4534,3 +4533,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Vászonméret automatikus módosítása Keep Relative Position During Layer Reordering Relatív pozíció megtartása a rétegek átrendezésekor Shrinkwrap Canvas on Save Vászon összehúzása a tartalomra mentéskor + Move Toolbar to the Right Eszköztár áthelyezése jobbra + Move Toolbar to the Left Eszköztár áthelyezése balra diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4ba6f52758..e5a4539eae 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -29,7 +29,7 @@ # Gradient Editor window, opened from the options bar's gradient swatch. -# Labels added on main after this catalog (depth labels, Wayland drop, profiles, Camera Raw, Patch tool, rendering mode) +# Labels added on main after this catalog (depth labels, Wayland drop, profiles, RAW Develop, Patch tool, rendering mode) # Warp grid presets (#388) @@ -319,7 +319,7 @@ Plugins… Plug-in… Type… Teks… Enhanced Controls… Kontrol Lanjutan… - Camera Raw… Camera Raw… + RAW Defaults… Default RAW… Raw Defaults… Default Raw… Integrations… Integrasi… AI Integrations… Integrasi AI… @@ -403,8 +403,8 @@ Artboard… Artboard… Artboard from Group… Artboard dari Grup… Artboard from Layers… Artboard dari Layer… - Layer via Copy Layer via Salin - Layer via Cut Layer via Potong + Layer Via Copy Layer via Salin + Layer Via Cut Layer via Potong Layer From Background… Layer dari Background… Layer from Background… Layer dari Background… Background From Layer Background dari Layer @@ -640,7 +640,7 @@ Last Filter Filter Terakhir Filter Gallery… Galeri Filter… Adaptive Wide Angle… Adaptive Wide Angle… - Camera Raw Filter… Filter Camera Raw… + RAW Develop Filter… Filter Pengembangan RAW… Liquify… Liquify… Vanishing Point… Vanishing Point… Blur Blur @@ -1010,8 +1010,8 @@ Load Settings… Muat Pengaturan… Save these settings as a Camera Raw .xmp file Simpan pengaturan ini sebagai berkas .xmp Camera Raw Load settings from a Camera Raw .xmp file Muat pengaturan dari berkas .xmp Camera Raw - Loaded Camera Raw settings from {file} Pengaturan Camera Raw dimuat dari {file} - Loaded Camera Raw settings from {file} ({n} not supported) Pengaturan Camera Raw dimuat dari {file} ({n} tidak didukung) + Loaded RAW Develop settings from {file} Pengaturan Pengembangan RAW dimuat dari {file} + Loaded RAW Develop settings from {file} ({n} not supported) Pengaturan Pengembangan RAW dimuat dari {file} ({n} tidak didukung) Begin recording Mulai merekam Bend: Lengkung: Bicubic Bicubic @@ -1039,7 +1039,7 @@ Brush Reconstruct Options Opsi Rekonstruksi Kuas Brush Tool Options Opsi Alat Kuas Cache Level: Level Cache: - Camera Raw isn't open Camera Raw tidak terbuka + RAW Develop isn't open Pengembangan RAW tidak terbuka Cancel Batal Cancel (Esc) Batal (Esc) Manage submitted jobs in the system print queue Kelola pekerjaan yang dikirim dalam antrean cetak sistem @@ -2001,7 +2001,7 @@ Brush preview color Warna pratinjau kuas Cache levels Level cache Cache tile size Ukuran tile cache - Camera Raw Defaults Default Camera Raw + RAW Defaults Default RAW Canvas border Border kanvas Show canvas dots Tampilkan titik kanvas Clip thumbnails to layer bounds Pangkas thumbnail ke batas layer @@ -2088,7 +2088,6 @@ Never Tidak pernah Normal tip Ujung normal Open as smart object Buka sebagai smart object - Open in camera raw Buka di Camera Raw Open documents as tabs Buka dokumen sebagai tab Overscroll Overscroll Performance Performa @@ -2489,8 +2488,6 @@ Roman Hanging Punctuation Tanda Baca Menggantung Roman Avoid Widows/Orphans Hindari Widow/Orphan Compose Komposisi - Adobe Single-line Composer Adobe Single-line Composer - Adobe Every-line Composer Adobe Every-line Composer Justification Justifikasi Word Spacing Spasi Kata Letter Spacing Spasi Huruf @@ -2745,7 +2742,6 @@ Intersect with Irisan dengan Capture Comp Tangkap Comp No Layer Comps Tidak Ada Layer Comp - Adobe PDF Presets… Preset Adobe PDF… 3D… 3D… Technology Previews… Pratinjau Teknologi… Background from Layer Background dari Layer @@ -2821,8 +2817,8 @@ Tone Histogram Histogram Nada Show Selected Region Tampilkan Wilayah Terpilih cameraRaw Light Cahaya - Camera Raw Filter ({layer}) Filter Camera Raw ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) Filter Pengembangan RAW ({layer}) + RAW Develop ({name}) Pengembangan RAW ({name}) cameraRaw Lights Nada Terang cameraRaw Darks Nada Gelap cameraRaw Blacks Hitam @@ -3523,8 +3519,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Gradasi Grayscale Current Colors Warna Saat Ini Make Ramp Web Safe Jadikan Gradasi Aman untuk Web + Scroll All Windows Gulir Semua Jendela The path was kept as the Work Path Path dipertahankan sebagai Work Path The path was discarded Path dibuang +# Art History Brush (#213). Art History Brush Tool Alat Kuas riwayat artistik Tight Short Rapet pendek Tight Medium Rapet sedang @@ -3629,6 +3627,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Pilih dokumen yang berbeda untuk setiap channel. A picked document is no longer open. Salah satu dokumen yang dipilih sudah tidak terbuka. A picked document is no longer a grayscale document of the same size. Salah satu dokumen yang dipilih bukan lagi dokumen grayscale dengan ukuran yang sama. + Netscape Gray Abu-abu Netscape # Move tool options bar (#11381) Align top edges Ratakan tepi atas Align vertical centers Ratakan pusat vertikal @@ -3638,7 +3637,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Tampilkan batas layer saat kursor di atasnya Expand layer group on click Perluas grup layer saat diklik Show hover bounds from Layers Tampilkan batas saat kursor di atas dari Layer - Saved Camera Raw settings to {file} Pengaturan Camera Raw disimpan ke {file} + Saved RAW Develop settings to {file} Pengaturan Pengembangan RAW disimpan ke {file} Save the settings to each raw's sidecar without opening it Simpan pengaturan ke file sidecar setiap raw tanpa membukanya No settings saved: these raws can't keep a sidecar here Tidak ada yang disimpan: raw ini tidak dapat memiliki file sidecar di sini Some settings could not be saved; the raws stay open Beberapa pengaturan tidak dapat disimpan; raw tetap terbuka @@ -3650,3 +3649,9 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Ubah ukuran kanvas otomatis Keep Relative Position During Layer Reordering Pertahankan posisi relatif saat mengurutkan ulang layer Shrinkwrap Canvas on Save Kecilkan kanvas sesuai konten saat menyimpan + Move Toolbar to the Right Pindahkan bilah alat ke kanan + Move Toolbar to the Left Pindahkan bilah alat ke kiri + +# RAW Develop feature labels + RAW Develop Pengembangan RAW + RAW Develop Filter Filter Pengembangan RAW diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1d671feece..f2028e9e75 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -49,7 +49,7 @@ -# Camera Raw: contextual controls and window title +# RAW Develop: contextual controls and window title # Strings added on main after this catalog was written (2026-10). @@ -93,7 +93,7 @@ # Counted status messages and labels (#3454; adapted from PR #3821) # View › Guides › New Guide… › Color -# Dynamic labels (filter and adjustment parameters, Camera Raw, panels, dialogs) that the +# Dynamic labels (filter and adjustment parameters, RAW Develop, panels, dialogs) that the # other catalogs already translate # Path, channel, layer style, status and System Info labels the Czech catalog added @@ -111,7 +111,7 @@ # Darken / Lighten Interface (⇧⌘F1 / ⇧⌘F2) # Bevel & Emboss Technique. -# Color management, Liquify, glyph group, warp and Camera Raw labels the Serbian, Vietnamese and Japanese catalogs added +# Color management, Liquify, glyph group, warp and RAW Develop labels the Serbian, Vietnamese and Japanese catalogs added # Shortcut commands, find and replace, profile prompts and metadata labels the German, Hungarian and Serbian catalogs added # View › Guides › right-click a guide @@ -342,7 +342,7 @@ Plugins… Plug-in… Type… Testo… Enhanced Controls… Controlli avanzati… - Camera Raw… Camera Raw… + RAW Defaults… Predefiniti RAW… Raw Defaults… Predefiniti Raw… Integrations… Integrazioni… AI Integrations… Integrazioni IA… @@ -431,8 +431,8 @@ Artboard… Tavola da disegno… Artboard from Group… Tavola da gruppo… Artboard from Layers… Tavola da livelli… - Layer via Copy Livello tramite copia - Layer via Cut Livello tramite taglia + Layer Via Copy Livello tramite copia + Layer Via Cut Livello tramite taglia Layer From Background… Livello dallo sfondo… Layer from Background… Livello dallo sfondo… Background from Layer Sfondo da livello @@ -674,7 +674,7 @@ Last Filter Ultimo filtro Filter Gallery… Galleria filtri… Adaptive Wide Angle… Grandangolo adattivo… - Camera Raw Filter… Filtro Camera Raw… + RAW Develop Filter… Filtro Sviluppo RAW… Liquify… Fluidifica… Vanishing Point… Punto di fuga… Blur Sfocatura @@ -1026,8 +1026,8 @@ Load Settings… Carica impostazioni… Save these settings as a Camera Raw .xmp file Salva queste impostazioni come file .xmp di Camera Raw Load settings from a Camera Raw .xmp file Carica le impostazioni da un file .xmp di Camera Raw - Loaded Camera Raw settings from {file} Impostazioni Camera Raw caricate da {file} - Loaded Camera Raw settings from {file} ({n} not supported) Impostazioni Camera Raw caricate da {file} ({n} non supportate) + Loaded RAW Develop settings from {file} Impostazioni Sviluppo RAW caricate da {file} + Loaded RAW Develop settings from {file} ({n} not supported) Impostazioni Sviluppo RAW caricate da {file} ({n} non supportate) Begin recording Inizia registrazione Bend: Curvatura: Bicubic Bicubica @@ -1055,7 +1055,7 @@ Brush Reconstruct Options Opzioni ricostruzione pennello Brush Tool Options Opzioni strumento Pennello Cache Level: Livello cache: - Camera Raw isn't open Camera Raw non è aperto + RAW Develop isn't open Sviluppo RAW non è aperto Cancel Annulla Reset Ripristina Cancel (Esc) Annulla (Esc) @@ -2029,7 +2029,7 @@ Brush preview color Colore anteprima pennello Cache levels Livelli cache Cache tile size Dimensione tile cache - Camera Raw Defaults Predefiniti Camera Raw + RAW Defaults Predefiniti RAW Canvas border Bordo quadro Show canvas dots Mostra punti del quadro Clip thumbnails to layer bounds Ritaglia le miniature ai limiti del livello @@ -2116,7 +2116,6 @@ Never Mai Normal tip Punta normale Open as smart object Apri come oggetto avanzato - Open in camera raw Apri in Camera Raw Open documents as tabs Apri documenti come schede Overscroll Overscroll Performance Prestazioni @@ -2480,8 +2479,8 @@ Tone Histogram Istogramma tonale Show Selected Region Mostra regione selezionata cameraRaw Light Luce - Camera Raw Filter ({layer}) Filtro Camera Raw ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) Filtro Sviluppo RAW ({layer}) + RAW Develop ({name}) Sviluppo RAW ({name}) cameraRaw Lights Toni chiari cameraRaw Darks Toni scuri cameraRaw Red Rossi @@ -3061,8 +3060,6 @@ curves Smooth Leviga Roman Hanging Punctuation Punteggiatura latina sospesa Avoid Widows/Orphans Evita righe vedove/orfane Compose Composizione - Adobe Single-line Composer Compositore riga singola Adobe - Adobe Every-line Composer Compositore ogni riga Adobe Word Spacing Spaziatura parole Letter Spacing Spaziatura lettere Glyph Scaling Ridimensionamento glifi @@ -3259,7 +3256,6 @@ curves Smooth Leviga Intersect with Interseca con Capture Comp Acquisisci composizione No Layer Comps Nessuna composizione livelli - Adobe PDF Presets… Predefiniti Adobe PDF… 3D… 3D… Technology Previews… Anteprime tecnologiche… Add a mask (from the selection; ⌥ inverts) Aggiungi una maschera (dalla selezione; ⌥ inverte) @@ -3899,8 +3895,8 @@ layerLabel No Color Nessun colore Border Bordo Box Blur Sfocatura casella Calculations Calcoli - Camera Raw Camera Raw - Camera Raw Filter Filtro Camera Raw + RAW Develop Sviluppo RAW + RAW Develop Filter Filtro Sviluppo RAW Channel1 Canale 1 Channel2 Canale 2 Channel3 Canale 3 @@ -4170,7 +4166,7 @@ layerLabel No Color Nessun colore Scroll menu down Scorri il menu in basso This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? Per procedere il livello di testo deve essere rasterizzato. Il testo non sarà più modificabile. Rasterizzare il testo? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Per procedere il livello forma deve essere rasterizzato. Non sarà più modificabile come forma. Rasterizzare la forma? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Per procedere l'oggetto avanzato deve essere rasterizzato. Il contenuto non sarà più modificabile. Rasterizzare l'oggetto avanzato? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Per procedere l'oggetto avanzato deve essere rasterizzato. Il contenuto non sarà più modificabile. Rasterizzare l'oggetto avanzato? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Per procedere il livello di riempimento deve essere rasterizzato. Il riempimento non sarà più modificabile. Rasterizzare il livello? This layer must be rasterized before proceeding. Per procedere il livello deve essere rasterizzato. Color Picker (Background Color) Selettore colore (colore sfondo) @@ -4343,7 +4339,6 @@ navigator Zoom Zoom Do not append "copy" to filename when saving a copy Non aggiungere "copy" al nome del file quando si salva una copia Save Full-Size Composite in .pcraft Files Salva l'immagine composita a dimensione piena nei file .pcraft Adobe-rgb-compat Adobe RGB (compatibile) - All shortcuts reset to Photoshop defaults. Tutte le scorciatoie ripristinate ai predefiniti di Photoshop. Arc Lower Arco inferiore Arc Upper Arco superiore Arrows Frecce @@ -4360,7 +4355,6 @@ navigator Zoom Zoom Convert Converti Currency Valute Cyrillic Cirillico - Default Photoshop Size Dimensione predefinita di Photoshop Display-p3 Display P3 Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · {commit} commits · Esc cancels Trascina un riquadro ritaglio · trascina dentro per spostare · bordi ridimensionano ({ratio} proporzione, {centre} centro) · Spazio sposta durante disegno · {commit} conferma · Esc annulla Drag: draw freehand · Release on the start point: close Trascina: disegna a mano libera · Rilascia sul punto iniziale: chiudi @@ -4619,8 +4613,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Barra scala di grigio Current Colors Colori correnti Make Ramp Web Safe Limita la barra ai colori web + Scroll All Windows Scorri tutte le finestre The path was kept as the Work Path Il tracciato è stato conservato come tracciato di lavoro The path was discarded Il tracciato è stato scartato +# Art History Brush (#213). Art History Brush Tool Strumento Pennello storia artistica Tight Short Corto stretto Tight Medium Medio stretto @@ -4705,6 +4701,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Scegli un documento diverso per ogni canale. A picked document is no longer open. Uno dei documenti scelti non è più aperto. A picked document is no longer a grayscale document of the same size. Uno dei documenti scelti non è più un documento in scala di grigio delle stesse dimensioni. + Netscape Gray Grigio Netscape # Move tool options bar (#11381) Align top edges Allinea i bordi superiori Align vertical centers Allinea i centri verticali @@ -4714,7 +4711,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Mostra i limiti del livello al passaggio del mouse Expand layer group on click Espandi il gruppo di livelli al clic Show hover bounds from Layers Mostra i limiti al passaggio dal pannello Livelli - Saved Camera Raw settings to {file} Impostazioni Camera Raw salvate in {file} + Saved RAW Develop settings to {file} Impostazioni Sviluppo RAW salvate in {file} Save the settings to each raw's sidecar without opening it Salva le impostazioni nel file sidecar di ogni raw senza aprirlo No settings saved: these raws can't keep a sidecar here Nulla salvato: questi raw non possono avere un file sidecar qui Some settings could not be saved; the raws stay open Alcune impostazioni non sono state salvate; i raw restano aperti @@ -4726,3 +4723,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Ridimensiona quadro automaticamente Keep Relative Position During Layer Reordering Mantieni la posizione relativa durante il riordino dei livelli Shrinkwrap Canvas on Save Riduci il quadro al contenuto al salvataggio + Move Toolbar to the Right Sposta la barra degli strumenti a destra + Move Toolbar to the Left Sposta la barra degli strumenti a sinistra diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c464084b38..ff4a65e0a5 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -42,7 +42,7 @@ # Strings added to the UI after this catalog was first written (rebase onto main, 2026-10). # Gradient Editor window, opened from the options bar's gradient swatch. # Rendering mode and recovery -# Camera Raw: contextual controls and window title +# RAW Develop: contextual controls and window title @@ -352,7 +352,7 @@ Plugins… プラグイン… Type… 文字… Enhanced Controls… 拡張コントロール… - Camera Raw… Camera Raw… + RAW Defaults… RAWの既定値… Raw Defaults… RAW の既定値… Integrations… 連携… AI Integrations… AI 連携… @@ -441,8 +441,8 @@ Artboard… アートボード… Artboard from Group… グループからアートボード… Artboard from Layers… レイヤーからアートボード… - Layer via Copy コピーしたレイヤー - Layer via Cut 切り取ったレイヤー + Layer Via Copy コピーしたレイヤー + Layer Via Cut 切り取ったレイヤー Layer From Background… 背景からレイヤーへ… Layer from Background… 背景からレイヤーへ… Background From Layer レイヤーから背景 @@ -686,7 +686,7 @@ Last Filter 直前のフィルター Filter Gallery… フィルターギャラリー… Adaptive Wide Angle… 広角補正… - Camera Raw Filter… Camera Raw フィルター… + RAW Develop Filter… RAW現像 フィルター… Liquify… ゆがみ… Vanishing Point… 消点… Blur ぼかし @@ -1041,8 +1041,8 @@ Load Settings… 設定を読み込み… Save these settings as a Camera Raw .xmp file この設定を Camera Raw の .xmp ファイルとして保存 Load settings from a Camera Raw .xmp file Camera Raw の .xmp ファイルから設定を読み込む - Loaded Camera Raw settings from {file} {file} から Camera Raw の設定を読み込みました - Loaded Camera Raw settings from {file} ({n} not supported) {file} から Camera Raw の設定を読み込みました(未対応: {n}) + Loaded RAW Develop settings from {file} {file} から RAW現像 の設定を読み込みました + Loaded RAW Develop settings from {file} ({n} not supported) {file} から RAW現像 の設定を読み込みました(未対応: {n}) Begin recording 記録を開始 Bend: 曲げ: Bicubic バイキュービック @@ -1070,7 +1070,7 @@ Brush Reconstruct Options ブラシの復元オプション Brush Tool Options ブラシツールのオプション Cache Level: キャッシュレベル: - Camera Raw isn't open Camera Raw は開いていません + RAW Develop isn't open RAW現像 は開いていません Cancel キャンセル Cancel (Esc) キャンセル(Esc) Manage submitted jobs in the system print queue 送信済みのジョブはシステムの印刷キューで管理してください @@ -2040,7 +2040,7 @@ Brush preview color ブラシプレビューの色 Cache levels キャッシュレベル Cache tile size キャッシュタイルのサイズ - Camera Raw Defaults Camera Raw の既定値 + RAW Defaults RAWの既定値 Canvas border カンバスの境界 Show canvas dots カンバスのドットを表示 Clip thumbnails to layer bounds サムネールをレイヤーの境界でクリップ @@ -2127,7 +2127,6 @@ Never しない Normal tip 通常の先端 Open as smart object スマートオブジェクトとして開く - Open in camera raw Camera Raw で開く Open documents as tabs ドキュメントをタブで開く Overscroll オーバースクロール Performance パフォーマンス @@ -2403,8 +2402,8 @@ Tone Histogram 階調ヒストグラム Show Selected Region 選択範囲を表示 cameraRaw Light ライト - Camera Raw Filter ({layer}) Camera Raw フィルター ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) RAW現像 フィルター ({layer}) + RAW Develop ({name}) RAW現像 ({name}) cameraRaw Lights 明部 cameraRaw Blending ブレンド cameraRaw Blacks 黒レベル @@ -2974,7 +2973,7 @@ fontWeight Italic 斜体 Box Blur ぼかし (ボックス) Bulge 膨らみ Burn 焼き込み - Camera Raw Filter Camera Raw フィルター + RAW Develop Filter RAW現像 フィルター Canvas Size カンバスサイズ Circularity 真円度 Clipping Path クリッピングパス @@ -3159,7 +3158,7 @@ fontWeight Italic 斜体 Border 境界 Browse 参照 Calculations 演算 - Camera Raw Camera Raw + RAW Develop RAW現像 Caption キャプション Category カテゴリー Channel チャンネル @@ -3345,10 +3344,7 @@ fontWeight Italic 斜体 Add to selection (⇧) 選択範囲に追加 (⇧) Adds grain to the soft edges of the brush tip. ブラシ先端の柔らかい縁に粒子を加えます。 Adjustment Layer 色調補正レイヤー - Adobe Every-line Composer Adobe 全行コンポーザー - Adobe PDF Presets… Adobe PDF プリセット… Adobe RGB (1998) Adobe RGB (1998) - Adobe Single-line Composer Adobe 1 行コンポーザー Advanced Controls 詳細コントロール After (X) 後 (X) Airbrush: keeps painting while the pointer rests. エアブラシ: ポインターを止めている間も描き続けます。 @@ -4184,8 +4180,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp グレースケールランプ Current Colors 現在のカラー Make Ramp Web Safe ランプを Web セーフにする + Scroll All Windows すべてのウィンドウをスクロール The path was kept as the Work Path パスは作業用パスとして保持されました The path was discarded パスは破棄されました +# Art History Brush (#213). Art History Brush Tool アートヒストリーブラシツール Tight Short タイト・ショート Tight Medium タイト・ミディアム @@ -4277,6 +4275,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. チャンネルごとに別のドキュメントを選択してください。 A picked document is no longer open. 選択したドキュメントの一つが開かれていません。 A picked document is no longer a grayscale document of the same size. 選択したドキュメントの一つが、同じサイズのグレースケールのドキュメントではなくなりました。 + Netscape Gray Netscape グレー # Move tool options bar (#11381) Align top edges 上端を揃える Align vertical centers 垂直方向中央を揃える @@ -4286,7 +4285,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover ホバー時にレイヤーの境界を表示 Expand layer group on click クリックでレイヤーグループを展開 Show hover bounds from Layers レイヤーパネルからのホバー境界を表示 - Saved Camera Raw settings to {file} Camera Raw の設定を {file} に保存しました + Saved RAW Develop settings to {file} RAW現像 の設定を {file} に保存しました Save the settings to each raw's sidecar without opening it 各 Raw のサイドカーファイルに設定を保存し、開かずに閉じます No settings saved: these raws can't keep a sidecar here 保存されませんでした:これらの Raw にはここでサイドカーファイルを作成できません Some settings could not be saved; the raws stay open 一部の設定を保存できませんでした。Raw は開いたままです @@ -4298,3 +4297,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas カンバスサイズを自動調整 Keep Relative Position During Layer Reordering レイヤーの並べ替え中も相対位置を保持 Shrinkwrap Canvas on Save 保存時にカンバスを内容に合わせて縮小 + Move Toolbar to the Right ツールバーを右へ移動 + Move Toolbar to the Left ツールバーを左へ移動 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 02e5270e11..6fea5cc544 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -195,7 +195,7 @@ Plug-ins… პლაგინები… Type… ტექსტი… Enhanced Controls… გაუმჯობესებული მართვის ელემენტები… - Camera Raw… Camera Raw… + RAW Defaults… RAW-ის ნაგულისხმევი პარამეტრები… Raw Defaults… Raw-ის ნაგულისხმევი პარამეტრები… Integrations… ინტეგრაციები… AI Integrations… AI ინტეგრაციები… @@ -276,8 +276,8 @@ Artboard… სამუშაო დაფა… Artboard from Group… სამუშაო დაფა ჯგუფიდან… Artboard from Layers… სამუშაო დაფა შრეებიდან… - Layer via Copy შრე კოპირებით - Layer via Cut შრე ამოჭრით + Layer Via Copy შრე კოპირებით + Layer Via Cut შრე ამოჭრით Layer From Background… შრე ფონიდან… Layer from Background… შრე ფონიდან… Background From Layer ფონი შრიდან @@ -507,7 +507,7 @@ Last Filter ბოლო ფილტრი Filter Gallery… ფილტრების გალერეა… Adaptive Wide Angle… ადაპტიური ფართოკუთხა… - Camera Raw Filter… Camera Raw ფილტრი… + RAW Develop Filter… RAW დამუშავება ფილტრი… Liquify… გათხევადება… Vanishing Point… გაქრობის წერტილი… Blur გაბუნდოვნება @@ -857,7 +857,7 @@ Brush Reconstruct Options ფუნჯით აღდგენის პარამეტრები Brush Tool Options ფუნჯის ხელსაწყოს პარამეტრები Cache Level: ქეშის დონე: - Camera Raw isn't open Camera Raw არ არის გახსნილი + RAW Develop isn't open RAW დამუშავება არ არის გახსნილი Cancel გაუქმება Cancel (Esc) გაუქმება (Esc) Cancel any current edits (Esc) მიმდინარე ცვლილებების გაუქმება (Esc) @@ -1811,7 +1811,7 @@ Brush preview color ფუნჯის წინასწარი ნახვის ფერი Cache levels ქეშის დონეები Cache tile size ქეშის ფილის ზომა - Camera Raw Defaults Camera Raw-ის ნაგულისხმევი პარამეტრები + RAW Defaults RAW-ის ნაგულისხმევი პარამეტრები Canvas border ტილოს საზღვარი Show canvas dots ტილოს წერტილების ჩვენება Canvas color ტილოს ფერი @@ -1891,7 +1891,6 @@ Never არასოდეს Normal tip ჩვეულებრივი წვერი Open as smart object ჭკვიან ობიექტად გახსნა - Open in camera raw Camera Raw-ში გახსნა Open documents as tabs დოკუმენტების ჩანართებად გახსნა Overscroll საზღვრებს მიღმა გადახვევა Performance წარმადობა @@ -2276,8 +2275,6 @@ Roman Hanging Punctuation ლათინური გამოწეული პუნქტუაცია Avoid Widows/Orphans ობოლი სტრიქონების თავიდან აცილება Compose აწყობა - Adobe Single-line Composer Adobe-ის სტრიქონის მიხედვით აწყობა - Adobe Every-line Composer Adobe-ის აბზაცის მიხედვით აწყობა Justification სწორება Word Spacing სიტყვებს შორის ინტერვალი Letter Spacing ასოებს შორის ინტერვალი @@ -2530,7 +2527,6 @@ Intersect with გადაკვეთა: Capture Comp კომპოზიციის ჩაწერა No Layer Comps შრეების კომპოზიციები არ არის - Adobe PDF Presets… Adobe PDF-ის პრესეტები… 3D… 3D… Technology Previews… ტექნოლოგიების წინასწარი ვერსიები… Background from Layer ფონი შრიდან @@ -2618,8 +2614,8 @@ Tone Histogram ტონების ჰისტოგრამა Show Selected Region მონიშნული რეგიონის ჩვენება cameraRaw Light სინათლე - Camera Raw Filter ({layer}) Camera Raw ფილტრი ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) RAW დამუშავება ფილტრი ({layer}) + RAW Develop ({name}) RAW დამუშავება ({name}) cameraRaw Lights ნათელი ტონები cameraRaw Darks მუქი ტონები cameraRaw Blacks შავები @@ -3615,8 +3611,8 @@ layerLabel No Color ფერის გარეშე Border საზღვარი Box Blur კვადრატული გაბუნდოვნება Calculations გამოთვლები - Camera Raw Camera Raw - Camera Raw Filter Camera Raw ფილტრი + RAW Develop RAW დამუშავება + RAW Develop Filter RAW დამუშავება ფილტრი Channel1 არხი1 Channel2 არხი2 Channel3 არხი3 @@ -3949,7 +3945,7 @@ curves Smooth გაგლუვება Scroll menu down მენიუს ქვემოთ გადახვევა This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? გასაგრძელებლად ეს ტექსტის შრე უნდა დარასტრირდეს. მისი ტექსტი აღარ იქნება რედაქტირებადი. დავარასტრირო ტექსტი? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? გასაგრძელებლად ეს ფიგურის შრე უნდა დარასტრირდეს. ის ფიგურად აღარ იქნება რედაქტირებადი. დავარასტრირო ფიგურა? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? გასაგრძელებლად ეს ჭკვიანი ობიექტი უნდა დარასტრირდეს. მისი შიგთავსი აღარ იქნება რედაქტირებადი. დავარასტრირო ჭკვიანი ობიექტი? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? გასაგრძელებლად ეს ჭკვიანი ობიექტი უნდა დარასტრირდეს. მისი შიგთავსი აღარ იქნება რედაქტირებადი. დავარასტრირო ჭკვიანი ობიექტი? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? გასაგრძელებლად ეს შევსების შრე უნდა დარასტრირდეს. მისი შევსება აღარ იქნება რედაქტირებადი. დავარასტრირო შრე? This layer must be rasterized before proceeding. გასაგრძელებლად ეს შრე უნდა დარასტრირდეს. Color Picker (Background Color) ფერის ამრჩევი (ფონის ფერი) @@ -4093,7 +4089,6 @@ shape Appearance იერსახე Add Mask to Selection ნიღბის მონიშნულში დამატება Add Open Files გახსნილი ფაილების დამატება Add to Dictionary ლექსიკონში დამატება - All shortcuts reset to Photoshop defaults. ყველა მალსახმობი დაბრუნდა Photoshop-ის ნაგულისხმევზე. Allow Continue გაგრძელების დაშვება Attempt to Automatically Align Source Images წყაროს გამოსახულებების ავტომატური სწორების მცდელობა Auto Add/Delete ავტომატური დამატება/წაშლა @@ -4114,7 +4109,6 @@ shape Appearance იერსახე Color Indicates: ფერი აღნიშნავს: Copy Texture to Other Tools ტექსტურის სხვა ხელსაწყოებში კოპირება Create Smart Object after Loading Layers შრეების ჩატვირთვის შემდეგ ჭკვიანი ობიექტის შექმნა - Default Photoshop Size Photoshop-ის ნაგულისხმევი ზომა Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · {commit} commits · Esc cancels გადაათრიეთ ჩამოჭრის ჩარჩო · შიგნით გადათრევით გადაადგილება · კიდეებით ზომის შეცვლა ({ratio} თანაფარდობა, {centre} ცენტრიდან) · Space — გადაადგილება ხაზვისას · {commit} — დადასტურება · Esc — გაუქმება Drag to pan · Scroll to zoom · Double-click to fit გადათრევა: გადაადგილება · გადახვევა: მასშტაბი · ორმაგი დაწკაპუნება: ჩატევა Drag: draw freehand · Release on the start point: close გადათრევა: თავისუფალი ხატვა · გაშვება საწყის წერტილზე: დახურვა @@ -4133,8 +4127,8 @@ shape Appearance იერსახე Load Actions… მოქმედებების ჩატვირთვა… Load Settings… პარამეტრების ჩატვირთვა… Load settings from a Camera Raw .xmp file პარამეტრების ჩატვირთვა Camera Raw-ის .xmp ფაილიდან - Loaded Camera Raw settings from {file} Camera Raw-ის პარამეტრები ჩაიტვირთა {file}-დან - Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw-ის პარამეტრები ჩაიტვირთა {file}-დან (მხარდაუჭერელი: {n}) + Loaded RAW Develop settings from {file} RAW დამუშავება-ის პარამეტრები ჩაიტვირთა {file}-დან + Loaded RAW Develop settings from {file} ({n} not supported) RAW დამუშავება-ის პარამეტრები ჩაიტვირთა {file}-დან (მხარდაუჭერელი: {n}) Mask Channel ნიღბის არხი Message: შეტყობინება: No Spelling Suggestions მართლწერის შეთავაზებები არ არის @@ -4595,9 +4589,9 @@ layerLabel Magenta მეწამული @plural {n} document|{n} documents {n} დოკუმენტი @plural {n} pixel|{n} pixels {n} პიქსელი cameraRaw Before (Y) მანამდე (Y) -cameraRaw Camera Raw ({name}) Camera Raw ({name}) -cameraRaw Camera Raw Filter ({layer}) Camera Raw ფილტრი ({layer}) -cameraRaw Camera Raw isn't open Camera Raw არ არის გახსნილი +cameraRaw RAW Develop ({name}) RAW დამუშავება ({name}) +cameraRaw RAW Develop Filter ({layer}) RAW დამუშავება ფილტრი ({layer}) +cameraRaw RAW Develop isn't open RAW დამუშავება არ არის გახსნილი cameraRaw Cancel გაუქმება cameraRaw Cancelled opening {name} {name}-ის გახსნა გაუქმდა cameraRaw Cancelled {label} გაუქმდა: {label} @@ -4609,7 +4603,7 @@ cameraRaw Highlight Clipping Warning (O) ღია ტონების მო cameraRaw Highlight Priority ღია ტონების პრიორიტეტი cameraRaw Load Settings… პარამეტრების ჩატვირთვა… cameraRaw Load settings from a Camera Raw .xmp file პარამეტრების ჩატვირთვა Camera Raw-ის .xmp ფაილიდან -cameraRaw Loaded Camera Raw settings from {file} Camera Raw-ის პარამეტრები ჩაიტვირთა {file}-დან +cameraRaw Loaded RAW Develop settings from {file} RAW დამუშავება-ის პარამეტრები ჩაიტვირთა {file}-დან cameraRaw Noise Reduction ხმაურის შემცირება cameraRaw OK OK cameraRaw Open გახსნა @@ -4717,3 +4711,8 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. თითოეული არხისთვის სხვა დოკუმენტი აირჩიეთ. A picked document is no longer open. ერთ-ერთი არჩეული დოკუმენტი აღარ არის გახსნილი. A picked document is no longer a grayscale document of the same size. ერთ-ერთი არჩეული დოკუმენტი აღარ არის იმავე ზომის ნაცრისფერი ტონების დოკუმენტი. + Move Toolbar to the Right ხელსაწყოების პანელის მარჯვნივ გადატანა + Move Toolbar to the Left ხელსაწყოების პანელის მარცხნივ გადატანა + +# RAW Develop feature labels + Saved RAW Develop settings to {file} RAW დამუშავების პარამეტრები შენახულია {file}-ში diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4d4815caf2..9f591db831 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -323,7 +323,7 @@ Plugins… 플러그인… Type… 문자… Enhanced Controls… 고급 컨트롤… - Camera Raw… Camera Raw… + RAW Defaults… RAW 기본값… Raw Defaults… RAW 기본값… Integrations… 연동… AI Integrations… AI 연동… @@ -407,8 +407,8 @@ Artboard… 아트보드… Artboard from Group… 그룹으로 아트보드 만들기… Artboard from Layers… 레이어로 아트보드 만들기… - Layer via Copy 복사하여 레이어 만들기 - Layer via Cut 잘라내어 레이어 만들기 + Layer Via Copy 복사하여 레이어 만들기 + Layer Via Cut 잘라내어 레이어 만들기 Layer From Background… 배경에서 레이어 만들기… Layer from Background… 배경에서 레이어 만들기… Background from Layer 레이어에서 배경 만들기 @@ -651,7 +651,7 @@ Last Filter 마지막 필터 Filter Gallery… 필터 갤러리… Adaptive Wide Angle… 응용 광각… - Camera Raw Filter… Camera Raw 필터… + RAW Develop Filter… RAW 현상 필터… Liquify… 픽셀 유동화… Vanishing Point… 소실점… Blur 흐림 효과 @@ -1011,8 +1011,8 @@ Load Settings… 설정 불러오기… Save these settings as a Camera Raw .xmp file 이 설정을 Camera Raw .xmp 파일로 저장 Load settings from a Camera Raw .xmp file Camera Raw .xmp 파일에서 설정 불러오기 - Loaded Camera Raw settings from {file} {file}에서 Camera Raw 설정을 불러왔습니다 - Loaded Camera Raw settings from {file} ({n} not supported) {file}에서 Camera Raw 설정을 불러왔습니다 (미지원 {n}개) + Loaded RAW Develop settings from {file} {file}에서 RAW 현상 설정을 불러왔습니다 + Loaded RAW Develop settings from {file} ({n} not supported) {file}에서 RAW 현상 설정을 불러왔습니다 (미지원 {n}개) Begin recording 기록 시작 Bend: 구부림: Bicubic 쌍입방 @@ -1040,7 +1040,7 @@ Brush Reconstruct Options 브러시 재구성 옵션 Brush Tool Options 브러시 도구 옵션 Cache Level: 캐시 레벨: - Camera Raw isn't open Camera Raw가 열려 있지 않습니다 + RAW Develop isn't open RAW 현상가 열려 있지 않습니다 Cancel 취소 Reset 재설정 Cancel (Esc) 취소 (Esc) @@ -2014,7 +2014,7 @@ Brush preview color 브러시 미리 보기 색상 Cache levels 캐시 레벨 Cache tile size 캐시 타일 크기 - Camera Raw Defaults Camera Raw 기본값 + RAW Defaults RAW 기본값 Canvas border 캔버스 테두리 Show canvas dots 캔버스 점 표시 Clip thumbnails to layer bounds 썸네일을 레이어 경계로 자르기 @@ -2101,7 +2101,6 @@ Never 안 함 Normal tip 표준 브러시 끝 Open as smart object 스마트 오브젝트로 열기 - Open in camera raw Camera Raw에서 열기 Open documents as tabs 문서를 탭으로 열기 Overscroll 캔버스 밖으로 스크롤 Performance 성능 @@ -2391,8 +2390,8 @@ Tone Histogram 명도 히스토그램 Show Selected Region 선택한 영역 표시 cameraRaw Light 밝게 - Camera Raw Filter ({layer}) Camera Raw 필터 ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) RAW 현상 필터 ({layer}) + RAW Develop ({name}) RAW 현상 ({name}) cameraRaw Lights 밝은 중간 영역 cameraRaw Blending 혼합 cameraRaw Blacks 검정 계열 @@ -2734,7 +2733,7 @@ cameraRaw Color 색상 Color Settings 색상 설정 Assign Profile 프로파일 지정 Convert to Profile 프로파일로 변환 - Camera Raw Camera Raw + RAW Develop RAW 현상 Raw Defaults RAW 기본값 AI Integrations AI 연동 Install Plug-in 플러그인 설치 @@ -2787,7 +2786,7 @@ cameraRaw Color 색상 Save Selection 선택 영역 저장 Filter Gallery 필터 갤러리 Adaptive Wide Angle 응용 광각 - Camera Raw Filter Camera Raw 필터 + RAW Develop Filter RAW 현상 필터 Liquify 픽셀 유동화 Vanishing Point 소실점 Field Blur 필드 흐림 효과 @@ -3726,8 +3725,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp 회색 음영 램프 Current Colors 현재 색상 Make Ramp Web Safe 램프를 웹 안전 색상으로 만들기 + Scroll All Windows 모든 창 스크롤 The path was kept as the Work Path 패스가 작업 패스로 유지되었습니다 The path was discarded 패스가 삭제되었습니다 +# Art History Brush (#213). Art History Brush 아트 히스토리 브러시 Art History Brush Tool 아트 히스토리 브러시 도구 Tight Short 타이트 숏 @@ -3833,6 +3834,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. 채널마다 다른 문서를 선택하십시오. A picked document is no longer open. 선택한 문서 중 하나가 더 이상 열려 있지 않습니다. A picked document is no longer a grayscale document of the same size. 선택한 문서 중 하나가 더 이상 같은 크기의 회색 음영 문서가 아닙니다. + Netscape Gray Netscape 회색 # Rows that #8185 adds on top of the catalog above. Working CMY Plate 작업용 CMY 판 @@ -4024,7 +4026,7 @@ layerLabel No Color 색상 없음 Scroll menu down 메뉴 아래로 스크롤 This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? 계속하려면 이 문자 레이어를 래스터화해야 합니다. 이후에는 텍스트를 편집할 수 없습니다. 문자를 래스터화할까요? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? 계속하려면 이 도형 레이어를 래스터화해야 합니다. 이후에는 도형으로 편집할 수 없습니다. 도형을 래스터화할까요? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? 계속하려면 이 고급 개체를 래스터화해야 합니다. 이후에는 내용을 편집할 수 없습니다. 고급 개체를 래스터화할까요? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? 계속하려면 이 고급 개체를 래스터화해야 합니다. 이후에는 내용을 편집할 수 없습니다. 고급 개체를 래스터화할까요? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? 계속하려면 이 칠 레이어를 래스터화해야 합니다. 이후에는 칠 내용을 편집할 수 없습니다. 레이어를 래스터화할까요? This layer must be rasterized before proceeding. 계속하려면 이 레이어를 래스터화해야 합니다. Color Picker (Background Color) 색상 선택기(배경색) @@ -4188,7 +4190,7 @@ shape Appearance 화면 모양 Show layer bounds on hover 마우스를 올리면 레이어 경계 표시 Expand layer group on click 클릭하면 레이어 그룹 펼치기 Show hover bounds from Layers 레이어 패널에서 마우스를 올릴 때 경계 표시 - Saved Camera Raw settings to {file} Camera Raw 설정을 {file}에 저장했습니다 + Saved RAW Develop settings to {file} RAW 현상 설정을 {file}에 저장했습니다 Save the settings to each raw's sidecar without opening it 각 Raw의 사이드카 파일에 설정을 저장하고 열지 않습니다 No settings saved: these raws can't keep a sidecar here 저장된 항목 없음: 이 Raw 파일은 여기에 사이드카 파일을 둘 수 없습니다 Some settings could not be saved; the raws stay open 일부 설정을 저장할 수 없습니다. Raw 파일은 열린 상태로 유지됩니다 @@ -4200,3 +4202,5 @@ shape Appearance 화면 모양 Auto-size Canvas 캔버스 크기 자동 조정 Keep Relative Position During Layer Reordering 레이어 순서 변경 시 상대 위치 유지 Shrinkwrap Canvas on Save 저장 시 캔버스를 내용에 맞게 축소 + Move Toolbar to the Right 도구 모음을 오른쪽으로 이동 + Move Toolbar to the Left 도구 모음을 왼쪽으로 이동 diff --git a/crates/ui-egui/src/i18n/nb.tsv b/crates/ui-egui/src/i18n/nb.tsv index 83643360f3..abb2371fe9 100644 --- a/crates/ui-egui/src/i18n/nb.tsv +++ b/crates/ui-egui/src/i18n/nb.tsv @@ -185,8 +185,8 @@ Trap… Overlapping… # Layer - Layer via Copy Lag via kopiering - Layer via Cut Lag via utklipp + Layer Via Copy Lag via kopiering + Layer Via Cut Lag via utklipp Duplicate Layer… Dupliser lag… Duplicate… Dupliser… Delete Slett @@ -350,7 +350,7 @@ Last Filter Siste filter Filter Gallery… Filtergalleri… Liquify… Gjør flytende… - Camera Raw Filter… Camera Raw-filter… + RAW Develop Filter… RAW-fremkalling-filter… Adaptive Wide Angle… Adaptiv vidvinkel… Lens Correction… Objektivkorreksjon… Vanishing Point… Fluktpunkt… @@ -875,7 +875,7 @@ Working Black Plate Arbeidsplate for svart Working Gray Plate Arbeidsplate for grå -# Camera Raw and lens dialogs +# RAW Develop and lens dialogs Basic Grunnleggende Detail Detalj HSL/Grayscale HSL/gråtoner @@ -905,8 +905,8 @@ Luminance Smoothness Luminansjevnhet Vignetting Vignettering White Balance: As Shot Hvitbalanse: som fotografert - Camera Raw… Camera Raw… - Camera Raw isn't open Camera Raw er ikke åpen + RAW Defaults… RAW-standarder… + RAW Develop isn't open RAW-fremkalling er ikke åpen Dehaze Fjern dis Texture Tekstur Focal Length Brennvidde @@ -1177,8 +1177,6 @@ Roman Hanging Punctuation Antikva hengende tegnsetting Avoid Widows/Orphans Unngå enker/horunger Compose Komponer - Adobe Single-line Composer Adobe setter for én linje - Adobe Every-line Composer Adobe setter for hver linje Justification Justering Word Spacing Ordmellomrom Letter Spacing Bokstavavstand @@ -1760,8 +1758,8 @@ Load Settings… Last inn innstillinger… Save these settings as a Camera Raw .xmp file Lagre disse innstillingene som en Camera Raw .xmp-fil Load settings from a Camera Raw .xmp file Last inn innstillinger fra en Camera Raw .xmp-fil - Loaded Camera Raw settings from {file} Lastet inn Camera Raw-innstillinger fra {file} - Loaded Camera Raw settings from {file} ({n} not supported) Lastet inn Camera Raw-innstillinger fra {file} ({n} støttes ikke) + Loaded RAW Develop settings from {file} Lastet inn RAW-fremkalling-innstillinger fra {file} + Loaded RAW Develop settings from {file} ({n} not supported) Lastet inn RAW-fremkalling-innstillinger fra {file} ({n} støttes ikke) After (X) Etter (X) Original Original Current Gjeldende @@ -2348,7 +2346,7 @@ CPU (no GPU acceleration) CPU (ingen GPU-akselerasjon) Cache levels Buffernivåer Cache tile size Bufferflisstørrelse - Camera Raw Defaults Camera Raw-standarder + RAW Defaults RAW-standarder Canvas border Lerretkant Show canvas dots Vis lerretprikker Clip thumbnails to layer bounds Klipp miniatyrer til laggrensene @@ -2440,7 +2438,6 @@ Never Aldri Normal tip Normal spiss Open as smart object Åpne som smartobjekt - Open in camera raw Åpne i Camera Raw Open documents as tabs Åpne dokumenter som faner OpenGL OpenGL Orange Oransje @@ -2581,9 +2578,9 @@ Tone Histogram Tonehistogram Show Selected Region Vis valgt område cameraRaw Light Lys -# Camera Raw: contextual controls and window title - Camera Raw Filter ({layer}) Camera Raw-filter ({layer}) - Camera Raw ({name}) Camera Raw ({name}) +# RAW Develop: contextual controls and window title + RAW Develop Filter ({layer}) RAW-fremkalling-filter ({layer}) + RAW Develop ({name}) RAW-fremkalling ({name}) Aqua Akvamarin cameraRaw Amount Mengde cameraRaw Blacks Svarttoner @@ -3388,7 +3385,7 @@ curves Smooth Jevn ut {name} was changed by another app after it was opened or saved here. {name} ble endret av et annet program etter at den ble åpnet eller lagret her. Replace it with this document, or cancel and use File › Save As to keep both. Erstatt den med dette dokumentet, eller avbryt og bruk Fil › Lagre som for å beholde begge. -# Dynamic UI labels (fourth pass): filter and adjustment parameters, Camera Raw panels, +# Dynamic UI labels (fourth pass): filter and adjustment parameters, RAW Develop panels, # lighting, History/Layers/paths/channels menus, metadata, System Info, status templates and # dialog text that other catalogs already carry. Written from the meaning of the English labels # in the ordinary Russian graphics-editor vocabulary; no proprietary resource consulted. @@ -3414,13 +3411,11 @@ curves Smooth Jevn ut Adjustment Layers Justeringslag Adjustment Properties Egenskaper for justering Adjustment layers have nothing to transform Justeringslag har ingenting å transformere - Adobe PDF Presets… Adobe PDF-forvalg… Adobe-rgb-compat Adobe RGB-kompatibel Adwaita (Dark) Adwaita (mørk) Adwaita (Light) Adwaita (lys) After Etter Airbrush: keeps painting while the pointer rests. Airbrush: fortsetter å male mens pekeren hviler. - All shortcuts reset to Photoshop defaults. Alle hurtigtaster tilbakestilt til Photoshop-standard. Altitude Høyde Ambience Stemning Ambient Omgivelseslys @@ -3505,8 +3500,8 @@ curves Smooth Jevn ut Brush Type Penseltype Burlap Jutevev Calculations Beregninger - Camera Raw Camera Raw - Camera Raw Filter Camera Raw-filter + RAW Develop RAW-fremkalling + RAW Develop Filter RAW-fremkalling-filter Cancel transform Avbryt transformering Candle Light Levende lys Canvas Size Lerretstørrelse @@ -3653,7 +3648,6 @@ curves Smooth Jevn ut Deep Yellow Dyp gul Default Foreground and Background Colors Standard forgrunns- og bakgrunnsfarge Default Leaves Standardblader - Default Photoshop Size Standard Photoshop-størrelse Defaults Standarder Define Brush Preset Definer penselforvalg Define Custom Shape Definer egendefinert form @@ -4493,7 +4487,7 @@ curves Smooth Jevn ut The file could not be saved. Filen kunne ikke lagres. Thickness Tykkelse This Layer: Dette laget: - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Dette smartobjektet må rasteriseres før du fortsetter. Innholdet kan da ikke lenger redigeres. Rasterisere smartobjektet? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Dette smartobjektet må rasteriseres før du fortsetter. Innholdet kan da ikke lenger redigeres. Rasterisere smartobjektet? This adjustment ({key}) is kept as imported and can't be edited yet. Denne justeringen ({key}) beholdes som importert og kan ikke redigeres ennå. This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Dette fyllaget må rasteriseres før du fortsetter. Fyllinnholdet kan da ikke lenger redigeres. Rasterisere laget? This layer must be rasterized before proceeding. Dette laget må rasteriseres før du fortsetter. @@ -4705,6 +4699,7 @@ shape Appearance Utseende Grayscale Ramp Gråtonerampe Current Colors Gjeldende farger Make Ramp Web Safe Gjør rampen webtrygg + Scroll All Windows Rull alle vinduer # Art History Brush (#213). Art History Brush Tool Kunsthistorikkpensel Tight Short Stram kort @@ -4753,9 +4748,9 @@ shape Appearance Utseende @plural {n} document|{n} documents {n} dokument|{n} dokumenter @plural {n} pixel|{n} pixels {n} piksel|{n} piksler cameraRaw Before (Y) Før (Y) -cameraRaw Camera Raw ({name}) Camera Raw ({name}) -cameraRaw Camera Raw Filter ({layer}) Camera Raw-filter ({layer}) -cameraRaw Camera Raw isn't open Camera Raw er ikke åpen +cameraRaw RAW Develop ({name}) RAW-fremkalling ({name}) +cameraRaw RAW Develop Filter ({layer}) RAW-fremkalling-filter ({layer}) +cameraRaw RAW Develop isn't open RAW-fremkalling er ikke åpen cameraRaw Cancel Avbryt cameraRaw Canceled opening {name} Avbrøt åpning av {name} cameraRaw Canceled {label} Avbrøt {label} @@ -4767,7 +4762,7 @@ cameraRaw Highlight Clipping Warning (O) Advarsel for høylysklipping (O) cameraRaw Highlight Priority Høylysprioritet cameraRaw Load Settings… Last inn innstillinger… cameraRaw Load settings from a Camera Raw .xmp file Last inn innstillinger fra en Camera Raw .xmp-fil -cameraRaw Loaded Camera Raw settings from {file} Lastet inn Camera Raw-innstillinger fra {file} +cameraRaw Loaded RAW Develop settings from {file} Lastet inn RAW-fremkalling-innstillinger fra {file} cameraRaw Noise Reduction Støyreduksjon cameraRaw OK OK cameraRaw Open Åpne @@ -4813,6 +4808,7 @@ cameraRaw White Balance: As Shot Hvitbalanse: som fotografert Pick a different document for each channel. Velg et annet dokument for hver kanal. A picked document is no longer open. Et av de valgte dokumentene er ikke lenger åpent. A picked document is no longer a grayscale document of the same size. Et av de valgte dokumentene er ikke lenger et dokument i gråtoner av samme størrelse. + Netscape Gray Netscape-grå # Move tool options bar (#11381) Align top edges Juster øverste kanter Align vertical centers Juster loddrette midtpunkter @@ -4829,3 +4825,8 @@ cameraRaw White Balance: As Shot Hvitbalanse: som fotografert Auto-size Canvas Endre lerretstørrelse automatisk Keep Relative Position During Layer Reordering Behold relativ posisjon ved omordning av lag Shrinkwrap Canvas on Save Krymp lerretet til innholdet ved lagring + Move Toolbar to the Right Flytt verktøylinjen til høyre + Move Toolbar to the Left Flytt verktøylinjen til venstre + +# RAW Develop feature labels + Saved RAW Develop settings to {file} RAW-fremkallingsinnstillinger lagret i {file} diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 07088b2d3e..edcf31b20e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -284,7 +284,7 @@ Plugins… Plug-ins… Type… Tekst… Enhanced Controls… Uitgebreide bediening… - Camera Raw… Camera Raw… + RAW Defaults… RAW-standaardwaarden… Raw Defaults… Raw-standaardwaarden… Integrations… Integraties… AI Integrations… AI-integraties… @@ -373,8 +373,8 @@ Artboard… Tekengebied… Artboard from Group… Tekengebied uit groep… Artboard from Layers… Tekengebied uit lagen… - Layer via Copy Laag via kopiëren - Layer via Cut Laag via knippen + Layer Via Copy Laag via kopiëren + Layer Via Cut Laag via knippen Layer From Background… Laag uit achtergrond… Layer from Background… Laag uit achtergrond… Background From Layer Achtergrond uit laag @@ -617,7 +617,7 @@ Last Filter Laatste filter Filter Gallery… Filtergalerie… Adaptive Wide Angle… Adaptieve groothoek… - Camera Raw Filter… Camera Raw-filter… + RAW Develop Filter… RAW-ontwikkeling-filter… Liquify… Uitvloeien… Vanishing Point… Verdwijnpunt… Blur Vervagen @@ -962,8 +962,8 @@ Load Settings… Instellingen laden… Save these settings as a Camera Raw .xmp file Deze instellingen opslaan als Camera Raw-.xmp-bestand Load settings from a Camera Raw .xmp file Instellingen laden uit een Camera Raw-.xmp-bestand - Loaded Camera Raw settings from {file} Camera Raw-instellingen geladen uit {file} - Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw-instellingen geladen uit {file} ({n} niet ondersteund) + Loaded RAW Develop settings from {file} RAW-ontwikkeling-instellingen geladen uit {file} + Loaded RAW Develop settings from {file} ({n} not supported) RAW-ontwikkeling-instellingen geladen uit {file} ({n} niet ondersteund) Begin recording Opname starten Bend: Buiging: Bicubic Bicubisch @@ -990,7 +990,7 @@ Brush Reconstruct Options Opties reconstructiepenseel Brush Tool Options Opties penseelgereedschap Cache Level: Cacheniveau: - Camera Raw isn't open Camera Raw is niet geopend + RAW Develop isn't open RAW-ontwikkeling is niet geopend Cancel Annuleren Reset Herstellen Cancel (Esc) Annuleren (Esc) @@ -1961,7 +1961,7 @@ Brush preview color Kleur penseelvoorvertoning Cache levels Cacheniveaus Cache tile size Tegelgrootte cache - Camera Raw Defaults Standaardwaarden Camera Raw + RAW Defaults RAW-standaardwaarden Canvas border Canvasrand Show canvas dots Canvasstippen tonen Clip thumbnails to layer bounds Miniaturen bijsnijden tot laaggrenzen @@ -2048,7 +2048,6 @@ Never Nooit Normal tip Normale punt Open as smart object Openen als slim object - Open in camera raw Openen in Camera Raw Open documents as tabs Documenten openen als tabbladen Overscroll Doorscrollen Performance Prestaties @@ -2397,8 +2396,8 @@ 3 x 3 3 x 3 4 x 4 4 x 4 5 x 5 5 x 5 - Camera Raw Filter ({layer}) Camera Raw-filter ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) RAW-ontwikkeling-filter ({layer}) + RAW Develop ({name}) RAW-ontwikkeling ({name}) Edit Type Tekst bewerken Grid: Raster: Highlight Clipping Warning (O) Waarschuwing afsnijden hooglichten (O) @@ -3398,7 +3397,6 @@ cameraRaw Color Kleur Add Pins Spelden toevoegen Add a mask (from the selection; ⌥ inverts) Een masker toevoegen (vanuit de selectie; ⌥ keert om) Adds grain to the soft edges of the brush tip. Voegt korrel toe aan de zachte randen van de penseelpunt. - Adobe PDF Presets… Adobe PDF-voorinstellingen… Advanced Blending Geavanceerd overvloeien After (X) Na (X) Airbrush: keeps painting while the pointer rests. Airbrush: blijft schilderen zolang de aanwijzer stilstaat. @@ -3425,8 +3423,8 @@ cameraRaw Color Kleur Border Rand Box Blur Kadervervaging Calculations Berekeningen - Camera Raw Camera Raw - Camera Raw Filter Camera Raw-filter + RAW Develop RAW-ontwikkeling + RAW Develop Filter RAW-ontwikkeling-filter Canvas rotation Canvasrotatie Channel1 Kanaal 1 Channel2 Kanaal 2 @@ -3705,8 +3703,6 @@ cameraRaw Whites Witten Mac Crisp Mac helder Mac Strong Mac krachtig Mac Smooth Mac vloeiend - Adobe Single-line Composer Adobe-zetmachine per regel - Adobe Every-line Composer Adobe-zetmachine voor alle regels X X Y Y 30 fps 30 fps @@ -4265,8 +4261,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Grijswaardenbalk Current Colors Huidige kleuren Make Ramp Web Safe Balk beperken tot webkleuren + Scroll All Windows Alle vensters schuiven The path was kept as the Work Path Het pad is behouden als werkpad The path was discarded Het pad is weggegooid +# Art History Brush (#213). Art History Brush Tool Artistiek historiepenseel Tight Short Strak kort Tight Medium Strak middel @@ -4360,6 +4358,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Kies voor elk kanaal een ander document. A picked document is no longer open. Een gekozen document is niet meer geopend. A picked document is no longer a grayscale document of the same size. Een gekozen document is geen grijswaardendocument van hetzelfde formaat meer. + Netscape Gray Netscape-grijs # Move tool options bar (#11381) Align top edges Bovenranden uitlijnen Align vertical centers Verticale middens uitlijnen @@ -4369,7 +4368,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Laaggrenzen tonen bij aanwijzen Expand layer group on click Laaggroep uitvouwen bij klikken Show hover bounds from Layers Aanwijsgrenzen tonen vanuit Lagen - Saved Camera Raw settings to {file} Camera Raw-instellingen opgeslagen in {file} + Saved RAW Develop settings to {file} RAW-ontwikkeling-instellingen opgeslagen in {file} Save the settings to each raw's sidecar without opening it De instellingen in het sidecarbestand van elke raw opslaan zonder die te openen No settings saved: these raws can't keep a sidecar here Niets opgeslagen: deze raws kunnen hier geen sidecarbestand krijgen Some settings could not be saved; the raws stay open Sommige instellingen konden niet worden opgeslagen; de raws blijven open @@ -4381,3 +4380,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Canvasgrootte automatisch aanpassen Keep Relative Position During Layer Reordering Relatieve positie behouden bij het wijzigen van de laagvolgorde Shrinkwrap Canvas on Save Canvas bij opslaan verkleinen tot de inhoud + Move Toolbar to the Right Werkbalk naar rechts verplaatsen + Move Toolbar to the Left Werkbalk naar links verplaatsen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index b6dd0211f0..c2efc53089 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -327,7 +327,7 @@ Plugins… Wtyczki… Type… Tekst… Enhanced Controls… Ulepszone elementy sterujące… - Camera Raw… Camera Raw… + RAW Defaults… Domyślne ustawienia RAW… Raw Defaults… Domyślne ustawienia Raw… Integrations… Integracje… AI Integrations… Integracje AI… @@ -416,8 +416,8 @@ Artboard… Obszar roboczy… Artboard from Group… Obszar roboczy z grupy… Artboard from Layers… Obszar roboczy z warstw… - Layer via Copy Warstwa przez kopiowanie - Layer via Cut Warstwa przez wycięcie + Layer Via Copy Warstwa przez kopiowanie + Layer Via Cut Warstwa przez wycięcie Layer From Background… Warstwa z tła… Layer from Background… Warstwa z tła… Background From Layer Tło z warstwy @@ -662,7 +662,7 @@ Last Filter Ostatni filtr Filter Gallery… Galeria filtrów… Adaptive Wide Angle… Adaptacyjny szeroki kąt… - Camera Raw Filter… Filtr Camera Raw… + RAW Develop Filter… Filtr Wywoływanie RAW… Liquify… Skraplanie… Vanishing Point… Punkt zbieżności… Blur Rozmycie @@ -1030,8 +1030,8 @@ Load Settings… Wczytaj ustawienia… Save these settings as a Camera Raw .xmp file Zapisz te ustawienia jako plik .xmp Camera Raw Load settings from a Camera Raw .xmp file Wczytaj ustawienia z pliku .xmp Camera Raw - Loaded Camera Raw settings from {file} Wczytano ustawienia Camera Raw z pliku {file} - Loaded Camera Raw settings from {file} ({n} not supported) Wczytano ustawienia Camera Raw z pliku {file} (nieobsługiwane: {n}) + Loaded RAW Develop settings from {file} Wczytano ustawienia Wywoływanie RAW z pliku {file} + Loaded RAW Develop settings from {file} ({n} not supported) Wczytano ustawienia Wywoływanie RAW z pliku {file} (nieobsługiwane: {n}) Begin recording Rozpocznij nagrywanie Bend: Zgięcie: Bicubic Dwusześcienna @@ -1059,7 +1059,7 @@ Brush Reconstruct Options Opcje pędzla rekonstrukcji Brush Tool Options Opcje narzędzia Pędzel Cache Level: Poziom pamięci podręcznej: - Camera Raw isn't open Camera Raw nie jest otwarty + RAW Develop isn't open Wywoływanie RAW nie jest otwarty Cancel Anuluj Cancel (Esc) Anuluj (Esc) Manage submitted jobs in the system print queue Zarządzaj przesłanymi zadaniami w systemowej kolejce drukowania @@ -2026,7 +2026,7 @@ Brush preview color Kolor podglądu pędzla Cache levels Poziomy pamięci podręcznej Cache tile size Rozmiar kafla pamięci podręcznej - Camera Raw Defaults Domyślne ustawienia Camera Raw + RAW Defaults Domyślne ustawienia RAW Canvas border Obramowanie płótna Show canvas dots Pokaż kropki płótna Clip thumbnails to layer bounds Przycinaj miniatury do granic warstwy @@ -2513,8 +2513,6 @@ Roman Hanging Punctuation Wiszące znaki interpunkcyjne (łacińskie) Avoid Widows/Orphans Unikaj wdów i sierot Compose Skład - Adobe Single-line Composer Skład jednowierszowy Adobe - Adobe Every-line Composer Skład wielowierszowy Adobe Justification Justowanie Word Spacing Odstępy między wyrazami Letter Spacing Odstępy między literami @@ -2770,7 +2768,6 @@ Intersect with Część wspólna z Capture Comp Przechwyć kompozycję No Layer Comps Brak kompozycji warstw - Adobe PDF Presets… Ustawienia wstępne Adobe PDF… 3D… 3D… Technology Previews… Podglądy technologii… Background from Layer Tło z warstwy @@ -2848,7 +2845,7 @@ fontWeight Bold Pogrubiony fontWeight ExtraBold Ekstra gruby fontWeight Black Czarny fontWeight Italic Kursywa - Camera Raw Filter ({layer}) Filtr Camera Raw ({layer}) + RAW Develop Filter ({layer}) Filtr Wywoływanie RAW ({layer}) cameraRaw Lights Jasne tony cameraRaw Darks Ciemne tony cameraRaw Blacks Czernie @@ -3207,7 +3204,7 @@ cameraRaw Roughness Chropowatość Color Settings Ustawienia kolorów Assign Profile Przypisz profil Convert to Profile Konwertuj na profil - Camera Raw Camera Raw + RAW Develop Wywoływanie RAW Raw Defaults Domyślne ustawienia Raw AI Integrations Integracje AI Install Plug-in Zainstaluj wtyczkę @@ -3254,7 +3251,7 @@ cameraRaw Roughness Chropowatość Border Obramowanie Contract Zwęź Filter Gallery Galeria filtrów - Camera Raw Filter Filtr Camera Raw + RAW Develop Filter Filtr Wywoływanie RAW Liquify Skraplanie Vanishing Point Punkt zbieżności Field Blur Rozmycie pola @@ -3539,11 +3536,10 @@ cameraRaw Roughness Chropowatość Pick a screen pixel or press Esc to cancel Wybierz piksel ekranu lub naciśnij Esc, aby anulować Scroll to zoom Przewijaj, aby zmieniać powiększenie Drag to pan · Scroll to zoom · Double-click to fit Przeciągnij, aby przesunąć · Przewijaj, aby powiększyć · Kliknij dwukrotnie, aby dopasować - Open in camera raw Otwórz w Camera Raw System title bar Systemowy pasek tytułu More documents Więcej dokumentów Developing {name} Wywoływanie {name} - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop ({name}) Wywoływanie RAW ({name}) Show/Hide All Panels Pokaż/ukryj wszystkie panele Show/Hide Panels Pokaż/ukryj panele Could not open Nie można otworzyć @@ -4125,8 +4121,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Pasek skali szarości Current Colors Bieżące kolory Make Ramp Web Safe Ogranicz pasek do kolorów internetowych + Scroll All Windows Przewijaj wszystkie okna The path was kept as the Work Path Ścieżka została zachowana jako ścieżka robocza The path was discarded Ścieżka została odrzucona +# Art History Brush (#213). Art History Brush Tool Narzędzie Pędzel historii artystycznej Tight Short Ścisły krótki Tight Medium Ścisły średni @@ -4224,6 +4222,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Wybierz inny dokument dla każdego kanału. A picked document is no longer open. Jeden z wybranych dokumentów nie jest już otwarty. A picked document is no longer a grayscale document of the same size. Jeden z wybranych dokumentów nie jest już dokumentem w skali szarości o tym samym rozmiarze. + Netscape Gray Szarość Netscape # Move tool options bar (#11381) Align top edges Wyrównaj górne krawędzie Align vertical centers Wyrównaj środki w pionie @@ -4233,7 +4232,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Pokaż granice warstwy po najechaniu Expand layer group on click Rozwiń grupę warstw po kliknięciu Show hover bounds from Layers Pokaż granice po najechaniu z panelu Warstwy - Saved Camera Raw settings to {file} Zapisano ustawienia Camera Raw w {file} + Saved RAW Develop settings to {file} Zapisano ustawienia Wywoływanie RAW w {file} Save the settings to each raw's sidecar without opening it Zapisz ustawienia w pliku sidecar każdego pliku raw bez otwierania go No settings saved: these raws can't keep a sidecar here Nic nie zapisano: te pliki raw nie mogą tu mieć pliku sidecar Some settings could not be saved; the raws stay open Nie udało się zapisać niektórych ustawień; pliki raw pozostają otwarte @@ -4245,3 +4244,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Automatycznie zmieniaj rozmiar płótna Keep Relative Position During Layer Reordering Zachowaj położenie względne przy zmianie kolejności warstw Shrinkwrap Canvas on Save Przytnij płótno do zawartości przy zapisie + Move Toolbar to the Right Przenieś pasek narzędzi w prawo + Move Toolbar to the Left Przenieś pasek narzędzi w lewo diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 15fdbbdbeb..402245ed55 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -322,7 +322,7 @@ Plugins… Plug-ins… Type… Tipo… Enhanced Controls… Controles aprimorados… - Camera Raw… Camera Raw… + RAW Defaults… Padrões RAW… Raw Defaults… Padrões de Raw… Integrations… Integrações… AI Integrations… Integrações de IA… @@ -406,8 +406,8 @@ Artboard… Prancheta… Artboard from Group… Prancheta a partir de grupo… Artboard from Layers… Prancheta a partir de camadas… - Layer via Copy Camada via cópia - Layer via Cut Camada via recorte + Layer Via Copy Camada via cópia + Layer Via Cut Camada via recorte Layer From Background… Camada a partir do plano de fundo… Layer from Background… Camada a partir do plano de fundo… Background From Layer Plano de fundo a partir da camada @@ -640,7 +640,7 @@ Last Filter Último filtro Filter Gallery… Galeria de filtros… Adaptive Wide Angle… Grande angular adaptável… - Camera Raw Filter… Filtro Camera Raw… + RAW Develop Filter… Filtro Revelação RAW… Liquify… Liquefazer… Vanishing Point… Ponto de fuga… Blur Desfoque @@ -993,8 +993,8 @@ Load Settings… Carregar configurações… Save these settings as a Camera Raw .xmp file Salvar estas configurações como arquivo .xmp do Camera Raw Load settings from a Camera Raw .xmp file Carregar configurações de um arquivo .xmp do Camera Raw - Loaded Camera Raw settings from {file} Configurações do Camera Raw carregadas de {file} - Loaded Camera Raw settings from {file} ({n} not supported) Configurações do Camera Raw carregadas de {file} ({n} sem suporte) + Loaded RAW Develop settings from {file} Configurações do Revelação RAW carregadas de {file} + Loaded RAW Develop settings from {file} ({n} not supported) Configurações do Revelação RAW carregadas de {file} ({n} sem suporte) Begin recording Iniciar gravação Bend: Curvatura: Bicubic Bicúbica @@ -1022,7 +1022,7 @@ Brush Reconstruct Options Opções de reconstrução do pincel Brush Tool Options Opções da ferramenta Pincel Cache Level: Nível do cache: - Camera Raw isn't open Camera Raw não está aberto + RAW Develop isn't open Revelação RAW não está aberto Cancel Cancelar Cancel (Esc) Cancelar (Esc) Manage submitted jobs in the system print queue Gerencie os trabalhos enviados na fila de impressão do sistema @@ -1984,7 +1984,7 @@ Brush preview color Cor da visualização do pincel Cache levels Níveis do cache Cache tile size Tamanho do bloco do cache - Camera Raw Defaults Padrões do Camera Raw + RAW Defaults Padrões RAW Canvas border Borda da tela de pintura Show canvas dots Mostrar pontos da tela de pintura Clip thumbnails to layer bounds Recortar miniaturas aos limites da camada @@ -2071,7 +2071,6 @@ Never Nunca Normal tip Ponta normal Open as smart object Abrir como objeto inteligente - Open in camera raw Abrir no Camera Raw Open documents as tabs Abrir documentos como guias Overscroll Rolagem além dos limites Performance Desempenho @@ -2475,8 +2474,6 @@ Roman Hanging Punctuation Pontuação romana deslocada Avoid Widows/Orphans Evitar viúvas/órfãs Compose Compor - Adobe Single-line Composer Compositor de linha única Adobe - Adobe Every-line Composer Compositor de todas as linhas Adobe Justification Justificação Word Spacing Espaçamento entre palavras Letter Spacing Espaçamento entre letras @@ -2732,7 +2729,6 @@ Intersect with Fazer interseção com Capture Comp Capturar composição No Layer Comps Nenhuma composição de camadas - Adobe PDF Presets… Predefinições do Adobe PDF… 3D… 3D… Technology Previews… Prévias de tecnologia… Background from Layer Plano de fundo a partir da camada @@ -2823,8 +2819,8 @@ Tone Histogram Histograma de tons Show Selected Region Mostrar região selecionada cameraRaw Light Luz - Camera Raw Filter ({layer}) Filtro Camera Raw ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) Filtro Revelação RAW ({layer}) + RAW Develop ({name}) Revelação RAW ({name}) cameraRaw Lights Claros cameraRaw Darks Escuros cameraRaw Blacks Pretos @@ -3849,8 +3845,8 @@ layerLabel No Color Sem cor Border Borda Box Blur Desfoque de caixa Calculations Cálculos - Camera Raw Camera Raw - Camera Raw Filter Filtro do Camera Raw + RAW Develop Revelação RAW + RAW Develop Filter Filtro do Revelação RAW Channel1 Canal 1 Channel2 Canal 2 Channel3 Canal 3 @@ -4321,7 +4317,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded This layer must be rasterized before proceeding. Esta camada precisa ser rasterizada antes de continuar. This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? Esta camada de texto precisa ser rasterizada antes de continuar. O texto não poderá mais ser editado. Rasterizar o texto? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Esta camada de forma precisa ser rasterizada antes de continuar. Ela não poderá mais ser editada como forma. Rasterizar a forma? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Este objeto inteligente precisa ser rasterizado antes de continuar. O conteúdo não poderá mais ser editado. Rasterizar o objeto inteligente? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Este objeto inteligente precisa ser rasterizado antes de continuar. O conteúdo não poderá mais ser editado. Rasterizar o objeto inteligente? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Esta camada de preenchimento precisa ser rasterizada antes de continuar. O conteúdo do preenchimento não poderá mais ser editado. Rasterizar a camada? Graphics adapter: {adapter} Adaptador gráfico: {adapter} Backend: {backend} ({type}) Backend: {backend} ({type}) @@ -4433,8 +4429,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Rampa de tons de cinza Current Colors Cores atuais Make Ramp Web Safe Tornar rampa segura para a Web + Scroll All Windows Rolar todas as janelas The path was kept as the Work Path O demarcador foi mantido como demarcador de trabalho The path was discarded O demarcador foi descartado +# Art History Brush (#213). Art History Brush Tool Ferramenta Pincel do histórico da arte Tight Short Curto cerrado Tight Medium Médio cerrado @@ -4520,6 +4518,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Escolha um documento diferente para cada canal. A picked document is no longer open. Um dos documentos escolhidos não está mais aberto. A picked document is no longer a grayscale document of the same size. Um dos documentos escolhidos não é mais um documento em tons de cinza do mesmo tamanho. + Netscape Gray Cinza Netscape # Move tool options bar (#11381) Align top edges Alinhar bordas superiores Align vertical centers Alinhar centros verticais @@ -4529,7 +4528,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Mostrar limites da camada ao passar o cursor Expand layer group on click Expandir grupo de camadas ao clicar Show hover bounds from Layers Mostrar limites ao passar o cursor em Camadas - Saved Camera Raw settings to {file} Configurações do Camera Raw salvas em {file} + Saved RAW Develop settings to {file} Configurações do Revelação RAW salvas em {file} Save the settings to each raw's sidecar without opening it Salvar as configurações no arquivo sidecar de cada raw sem abri-lo No settings saved: these raws can't keep a sidecar here Nada foi salvo: estes raw não podem ter um arquivo sidecar aqui Some settings could not be saved; the raws stay open Não foi possível salvar algumas configurações; os raw continuam abertos @@ -4541,3 +4540,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Ajustar tamanho da tela automaticamente Keep Relative Position During Layer Reordering Manter a posição relativa ao reordenar camadas Shrinkwrap Canvas on Save Reduzir a tela ao conteúdo ao salvar + Move Toolbar to the Right Mover a barra de ferramentas para a direita + Move Toolbar to the Left Mover a barra de ferramentas para a esquerda diff --git a/crates/ui-egui/src/i18n/ro.tsv b/crates/ui-egui/src/i18n/ro.tsv index 5bf7d924c8..73e2427adf 100644 --- a/crates/ui-egui/src/i18n/ro.tsv +++ b/crates/ui-egui/src/i18n/ro.tsv @@ -30,7 +30,7 @@ # Tool, filter, warp-style, path, layer-comp and metadata names that fell outside the `tl!` test. # Command-id override: under Edit > Purge a bare "Undo" reads as an action, not the history. # Rendering mode and recovery -# Camera Raw: contextual controls and window title +# RAW Develop: contextual controls and window title # About ▸ Contributors / Models (credits, craftrules standards/contributors.md) # Swatches panel # Layer Style > Blending Options (Advanced Blending) @@ -55,7 +55,7 @@ # Print dialog (#2697) # Counted status messages and labels (#3454) # View › Guides › New Guide… › Color -# Dynamic labels (filter and adjustment parameters, Camera Raw, panels, dialogs) translated from +# Dynamic labels (filter and adjustment parameters, RAW Develop, panels, dialogs) translated from # the English source, following the pattern of the other complete catalogs. # Path, channel, layer style, status and System Info labels # Actions panel: Load/Save Actions (.atn) and kept Photoshop steps @@ -266,7 +266,7 @@ Plug-ins… Plugin-uri… Type… Text… Enhanced Controls… Controale îmbunătățite… - Camera Raw… Camera Raw… + RAW Defaults… Valori implicite RAW… Raw Defaults… Valori implicite Raw… Integrations… Integrări… AI Integrations… Integrări AI… @@ -353,8 +353,8 @@ Artboard… Planșă de lucru… Artboard from Group… Planșă de lucru din grup… Artboard from Layers… Planșă de lucru din straturi… - Layer via Copy Strat prin copiere - Layer via Cut Strat prin decupare + Layer Via Copy Strat prin copiere + Layer Via Cut Strat prin decupare Layer From Background… Strat din fundal… Layer from Background… Strat din fundal… Background from Layer Fundal din strat @@ -596,7 +596,7 @@ Last Filter Ultimul filtru Filter Gallery… Galerie de filtre… Adaptive Wide Angle… Unghi larg adaptabil… - Camera Raw Filter… Filtru Camera Raw… + RAW Develop Filter… Filtru Developare RAW… Liquify… Lichefiere… Vanishing Point… Punct de fugă… Blur Neclaritate @@ -944,8 +944,8 @@ Load Settings… Încărcare setări… Save these settings as a Camera Raw .xmp file Salvare acestor setări ca fișier .xmp Camera Raw Load settings from a Camera Raw .xmp file Încărcare setări dintr-un fișier .xmp Camera Raw - Loaded Camera Raw settings from {file} Setări Camera Raw încărcate din {file} - Loaded Camera Raw settings from {file} ({n} not supported) Setări Camera Raw încărcate din {file} ({n} nesuportate) + Loaded RAW Develop settings from {file} Setări Developare RAW încărcate din {file} + Loaded RAW Develop settings from {file} ({n} not supported) Setări Developare RAW încărcate din {file} ({n} nesuportate) Begin recording Pornire înregistrare Bend: Curbură: Bicubic Bicubică @@ -973,7 +973,7 @@ Brush Reconstruct Options Opțiuni reconstrucție pensulă Brush Tool Options Opțiuni instrument Pensulă Cache Level: Nivel cache: - Camera Raw isn't open Camera Raw nu este deschis + RAW Develop isn't open Developare RAW nu este deschis Cancel Anulare Cancel (Esc) Anulare (Esc) Manage submitted jobs in the system print queue Gestionarea lucrărilor trimise în coada de imprimare a sistemului @@ -1944,7 +1944,7 @@ Brush preview color Culoare previzualizare pensulă Cache levels Niveluri cache Cache tile size Dimensiune mozaic cache - Camera Raw Defaults Valori implicite Camera Raw + RAW Defaults Valori implicite RAW Canvas border Margine pânză Show canvas dots Afișare puncte pânză Clip thumbnails to layer bounds Decupare miniaturi la limitele stratului @@ -2026,7 +2026,6 @@ Never Niciodată Normal tip Vârf normal Open as smart object Deschidere ca obiect inteligent - Open in camera raw Deschidere în Camera Raw Open documents as tabs Deschidere documente ca file Overscroll Suprascrolare Performance Performanță @@ -2387,8 +2386,8 @@ Tone Histogram Histogramă tonală Show Selected Region Afișare regiune selectată cameraRaw Light Lumină - Camera Raw Filter ({layer}) Filtru Camera Raw ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) Filtru Developare RAW ({layer}) + RAW Develop ({name}) Developare RAW ({name}) cameraRaw Lights Luminile cameraRaw Darks Umbrele cameraRaw Red Roșii @@ -2985,8 +2984,6 @@ curves Smooth Netezire Roman Hanging Punctuation Punctuație latină suspendată Avoid Widows/Orphans Evitare linii văduve/orfane Compose Compunere - Adobe Single-line Composer Compozitor Adobe cu o linie - Adobe Every-line Composer Compozitor Adobe multilinie Word Spacing Spațiu între cuvinte Letter Spacing Spațiu între caractere Glyph Scaling Scalare glife @@ -3182,7 +3179,6 @@ curves Smooth Netezire Intersect with Intersectare cu Capture Comp Capturare compoziție No Layer Comps Nicio compoziție de strat - Adobe PDF Presets… Presetări Adobe PDF… 3D… 3D… Technology Previews… Previzualizări de tehnologie… Add a mask (from the selection; ⌥ inverts) Adăugare mască (din selecție; ⌥ inversează) @@ -3799,8 +3795,8 @@ layerLabel No Color Fără culoare Border Margine Box Blur Neclaritate cutie Calculations Calcule - Camera Raw Camera Raw - Camera Raw Filter Filtru Camera Raw + RAW Develop Developare RAW + RAW Develop Filter Filtru Developare RAW Channel1 Canal 1 Channel2 Canal 2 Channel3 Canal 3 @@ -4060,7 +4056,7 @@ layerLabel No Color Fără culoare Scroll menu down Derulare meniu jos This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? Acest strat de text trebuie rasterizat înainte de a continua. Textul său nu va mai fi editabil. Rasterizați textul? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Acest strat de formă trebuie rasterizat înainte de a continua. Nu va mai fi editabil ca formă. Rasterizați forma? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Acest obiect inteligent trebuie rasterizat înainte de a continua. Conținutul său nu va mai fi editabil. Rasterizați obiectul inteligent? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Acest obiect inteligent trebuie rasterizat înainte de a continua. Conținutul său nu va mai fi editabil. Rasterizați obiectul inteligent? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Acest strat de umplere trebuie rasterizat înainte de a continua. Conținutul său de umplere nu va mai fi editabil. Rasterizați stratul? This layer must be rasterized before proceeding. Acest strat trebuie rasterizat înainte de a continua. Color Picker (Background Color) Selector de culoare (culoare de fundal) @@ -4614,3 +4610,8 @@ navigator Zoom Zoom @plural {n} action file loaded|{n} action files loaded {n} fișier de acțiuni încărcat|{n} fișiere de acțiuni încărcate|{n} de fișiere de acțiuni încărcate @plural {n} file could not be loaded: {errors}|{n} files could not be loaded: {errors} {n} fișier nu a putut fi încărcat: {errors}|{n} fișiere nu au putut fi încărcate: {errors}|{n} de fișiere nu au putut fi încărcate: {errors} @plural {what}: {n} Image Assets output failed|{what}: {n} Image Assets outputs failed {what}: {n} ieșire Resurse imagine a eșuat|{what}: {n} ieșiri Resurse imagine au eșuat|{what}: {n} de ieșiri Resurse imagine au eșuat + Move Toolbar to the Right Mută bara de instrumente la dreapta + Move Toolbar to the Left Mută bara de instrumente la stânga + +# RAW Develop feature labels + Saved RAW Develop settings to {file} Setările de developare RAW au fost salvate în {file} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 65575eaf9a..41f8ad54f9 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -66,7 +66,7 @@ # Filters and adjustments dialogs -# Camera Raw and lens dialogs +# RAW Develop and lens dialogs # Adjustments panel @@ -125,7 +125,7 @@ # Preference dialog: generated setting labels and dropdown choices # Rendering mode and recovery -# Camera Raw: contextual controls and window title +# RAW Develop: contextual controls and window title @@ -199,7 +199,7 @@ # Preferences › Performance › GPU Memory; the status bar and slow-redraw notice -# Dynamic UI labels (fourth pass): filter and adjustment parameters, Camera Raw panels, +# Dynamic UI labels (fourth pass): filter and adjustment parameters, RAW Develop panels, # lighting, History/Layers/paths/channels menus, metadata, System Info, status templates and # dialog text that other catalogs already carry. Written from the meaning of the English labels # in the ordinary Russian graphics-editor vocabulary; no proprietary resource consulted. @@ -365,8 +365,8 @@ Duotone… Дуотон… Duotone Дуотон Trap… Приводка… - Layer via Copy Скопировать на новый слой - Layer via Cut Вырезать на новый слой + Layer Via Copy Скопировать на новый слой + Layer Via Cut Вырезать на новый слой Duplicate Layer… Дублировать слой… Duplicate… Дублировать… Delete Удалить @@ -523,7 +523,7 @@ Last Filter Последний фильтр Filter Gallery… Галерея фильтров… Liquify… Пластичность… - Camera Raw Filter… Фильтр Camera Raw… + RAW Develop Filter… Фильтр Обработка RAW… Adaptive Wide Angle… Адаптивный широкий угол… Lens Correction… Коррекция дисторсии… Vanishing Point… Точка схода… @@ -1055,8 +1055,8 @@ Luminance Smoothness Световая сглаженность Vignetting Виньетирование White Balance: As Shot Баланс белого: как снято - Camera Raw… Camera Raw… - Camera Raw isn't open Camera Raw не открыт + RAW Defaults… Настройки RAW по умолчанию… + RAW Develop isn't open Обработка RAW не открыт Dehaze Устранение дымки Texture Текстура Focal Length Фокусное расстояние @@ -1315,8 +1315,6 @@ Roman Hanging Punctuation Висячая пунктуация (римская) Avoid Widows/Orphans Избегать висячих строк Compose Компоновка - Adobe Single-line Composer Построчная компоновка Adobe - Adobe Every-line Composer Абзацная компоновка Adobe Justification Выключка Word Spacing Межсловные интервалы Letter Spacing Межбуквенные интервалы @@ -1872,8 +1870,8 @@ Load Settings… Загрузить настройки… Save these settings as a Camera Raw .xmp file Сохранить эти настройки в файл Camera Raw .xmp Load settings from a Camera Raw .xmp file Загрузить настройки из файла Camera Raw .xmp - Loaded Camera Raw settings from {file} Настройки Camera Raw загружены из {file} - Loaded Camera Raw settings from {file} ({n} not supported) Настройки Camera Raw загружены из {file} (не поддерживается: {n}) + Loaded RAW Develop settings from {file} Настройки Обработка RAW загружены из {file} + Loaded RAW Develop settings from {file} ({n} not supported) Настройки Обработка RAW загружены из {file} (не поддерживается: {n}) After (X) После (X) Original Оригинал Current Текущий @@ -2443,7 +2441,7 @@ CPU (no GPU acceleration) ЦП (без ускорения GPU) Cache levels Уровни кэша Cache tile size Размер блока кэша - Camera Raw Defaults Значения Camera Raw по умолчанию + RAW Defaults Настройки RAW по умолчанию Canvas border Рамка холста Show canvas dots Показывать точки холста Clip thumbnails to layer bounds Обрезать миниатюры по границам слоя @@ -2535,7 +2533,6 @@ Never Никогда Normal tip Контур кисти (50%) Open as smart object Открывать как смарт-объект - Open in camera raw Открывать в Camera Raw Open documents as tabs Открывать документы во вкладках OpenGL OpenGL Orange Оранжевая @@ -2675,8 +2672,8 @@ Tone Histogram Тональная гистограмма Show Selected Region Показать выделенную область cameraRaw Light Свет - Camera Raw Filter ({layer}) Фильтр Camera Raw ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) Фильтр Обработка RAW ({layer}) + RAW Develop ({name}) Обработка RAW ({name}) Aqua Голубой cameraRaw Amount Интенсивность cameraRaw Blacks Чёрные @@ -3441,13 +3438,11 @@ curves Smooth Сгладить Adjustment Layers Корректирующие слои Adjustment Properties Свойства коррекции Adjustment layers have nothing to transform В корректирующих слоях нечего трансформировать - Adobe PDF Presets… Наборы Adobe PDF… Adobe-rgb-compat Adobe RGB (совместимо) Adwaita (Dark) Adwaita (тёмная) Adwaita (Light) Adwaita (светлая) After После Airbrush: keeps painting while the pointer rests. Аэрограф: продолжает рисовать, пока указатель неподвижен. - All shortcuts reset to Photoshop defaults. Все сочетания клавиш сброшены к значениям Photoshop по умолчанию. Altitude Высота Ambience Атмосфера Ambient Окружающий свет @@ -3532,8 +3527,8 @@ curves Smooth Сгладить Brush Type Тип кисти Burlap Мешковина Calculations Вычисления - Camera Raw Camera Raw - Camera Raw Filter Фильтр Camera Raw + RAW Develop Обработка RAW + RAW Develop Filter Фильтр Обработка RAW Cancel transform Отменить трансформирование Candle Light Свет свечи Canvas Size Размер холста @@ -3680,7 +3675,6 @@ curves Smooth Сгладить Deep Yellow Глубокий жёлтый Default Foreground and Background Colors Цвета переднего плана и фона по умолчанию Default Leaves Листья по умолчанию - Default Photoshop Size Размер Photoshop по умолчанию Defaults По умолчанию Define Brush Preset Определить кисть Define Custom Shape Определить свою фигуру @@ -4496,7 +4490,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded The file could not be saved. Не удалось сохранить файл. Thickness Толщина This Layer: Этот слой: - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Перед продолжением необходимо растрировать этот смарт-объект. Его содержимое перестанет быть редактируемым. Растрировать смарт-объект? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Перед продолжением необходимо растрировать этот смарт-объект. Его содержимое перестанет быть редактируемым. Растрировать смарт-объект? This adjustment ({key}) is kept as imported and can't be edited yet. Эта коррекция ({key}) сохраняется в импортированном виде и пока не может быть изменена. This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Перед продолжением необходимо растрировать этот слой заливки. Содержимое заливки перестанет быть редактируемым. Растрировать слой? This layer must be rasterized before proceeding. Перед продолжением необходимо растрировать этот слой. @@ -4704,8 +4698,10 @@ shape Appearance Оформление Grayscale Ramp Шкала градаций серого Current Colors Текущие цвета Make Ramp Web Safe Сделать шкалу безопасной для web + Scroll All Windows Прокручивать все окна The path was kept as the Work Path Контур сохранён как рабочий контур The path was discarded Контур удалён +# Art History Brush (#213). Art History Brush Tool Инструмент «Кисть истории искусств» Tight Short Плотный короткий Tight Medium Плотный средний @@ -4791,6 +4787,7 @@ shape Appearance Оформление Pick a different document for each channel. Выберите отдельный документ для каждого канала. A picked document is no longer open. Один из выбранных документов больше не открыт. A picked document is no longer a grayscale document of the same size. Один из выбранных документов больше не является документом в градациях серого того же размера. + Netscape Gray Серый Netscape # Move tool options bar (#11381) Align top edges Выровнять верхние края Align vertical centers Выровнять центры по вертикали @@ -4800,7 +4797,7 @@ shape Appearance Оформление Show layer bounds on hover Показывать границы слоя при наведении Expand layer group on click Раскрывать группу слоёв по щелчку Show hover bounds from Layers Показывать границы при наведении из панели «Слои» - Saved Camera Raw settings to {file} Настройки Camera Raw сохранены в {file} + Saved RAW Develop settings to {file} Настройки Обработка RAW сохранены в {file} Save the settings to each raw's sidecar without opening it Сохранить настройки в сопроводительный файл каждого raw, не открывая его No settings saved: these raws can't keep a sidecar here Ничего не сохранено: у этих raw здесь не может быть сопроводительного файла Some settings could not be saved; the raws stay open Не удалось сохранить некоторые настройки; raw остаются открытыми @@ -4812,3 +4809,5 @@ shape Appearance Оформление Auto-size Canvas Автоматически менять размер холста Keep Relative Position During Layer Reordering Сохранять относительное положение при изменении порядка слоев Shrinkwrap Canvas on Save Уменьшать холст до содержимого при сохранении + Move Toolbar to the Right Переместить панель инструментов вправо + Move Toolbar to the Left Переместить панель инструментов влево diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index b2c1d42cab..e4c9c511b0 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -18,7 +18,7 @@ # (Datoteka, Uređivanje, Slika ...), commands are imperatives (Otvori…, Sačuvaj kao…), tools read # "Alatka …" (Alatka četkica, Alatka za pomeranje), presets are "šabloni", patterns "šare" and # swatches "uzorci boja". Serbian quotation marks „…“ around names. Product and technology names -# (PhotoCraft, ArtCraft, Camera Raw, OpenType, Lab ...) stay as they are; RGB/CMYK stay as they +# (PhotoCraft, ArtCraft, RAW Develop, OpenType, Lab ...) stay as they are; RGB/CMYK stay as they # are; the trailing "…" of dialog commands is kept. A count that is not an @plural entry is kept # out of noun agreement ("Broj: {n}", "slojeva: {n}") so every number reads correctly. @@ -34,7 +34,7 @@ # Labels added on main after this catalog (depth labels, Wayland drop, profiles, rendering mode) -# Camera Raw scopes and the Patch tool +# RAW Develop scopes and the Patch tool # Warp grid presets (#388) @@ -75,11 +75,11 @@ # Gradient Editor window, opened from the options bar's gradient swatch. -# Camera Raw: contextual controls and window title +# RAW Develop: contextual controls and window title # Counted status messages and labels (Serbian: one | few | many) -# Dynamic labels (filter and adjustment parameters, Camera Raw, panels, dialogs) +# Dynamic labels (filter and adjustment parameters, RAW Develop, panels, dialogs) # Path, channel, layer style, status and System Info labels the Czech catalog added @@ -91,14 +91,14 @@ # Character, Paragraph and Glyphs panels -# Camera Raw labels +# RAW Develop labels # Keyboard Shortcuts and Menus editor # Color Settings dialog -# Camera Raw chrome, tone, curve, color mixer, grading, detail and effects +# RAW Develop chrome, tone, curve, color mixer, grading, detail and effects # New Document, Home and Image Size @@ -106,7 +106,7 @@ # Contextual labels -# Added on merge with main (spelling, Camera Raw settings files, printing, Object Finder, brush +# Added on merge with main (spelling, RAW Develop settings files, printing, Object Finder, brush # controls, actions, gradient presets, Pen Auto Add/Delete) # Native Windows printing qualification @@ -348,7 +348,7 @@ Plugins… Dodaci… Type… Tekst… Enhanced Controls… Napredne kontrole… - Camera Raw… Camera Raw… + RAW Defaults… Podrazumevana RAW podešavanja… Raw Defaults… Podrazumevana Raw podešavanja… Integrations… Integracije… AI Integrations… AI integracije… @@ -431,8 +431,8 @@ Artboard… Radna tabla… Artboard from Group… Radna tabla od grupe… Artboard from Layers… Radna tabla od slojeva… - Layer via Copy Sloj kopiranjem - Layer via Cut Sloj isecanjem + Layer Via Copy Sloj kopiranjem + Layer Via Cut Sloj isecanjem Layer From Background… Sloj od pozadine… Layer from Background… Sloj od pozadine… Background From Layer Pozadina od sloja @@ -666,7 +666,7 @@ Last Filter Poslednji filter Filter Gallery… Galerija filtera… Adaptive Wide Angle… Prilagodljivi široki ugao… - Camera Raw Filter… Camera Raw filter… + RAW Develop Filter… RAW obrada filter… Liquify… Tečno izobličavanje… Vanishing Point… Tačka nestajanja… Blur Zamućenje @@ -1042,7 +1042,7 @@ Brush Reconstruct Options Opcije četkice za rekonstrukciju Brush Tool Options Opcije alatke četkica Cache Level: Nivo keša: - Camera Raw isn't open Camera Raw nije otvoren + RAW Develop isn't open RAW obrada nije otvoren Cancel Otkaži Cancel (Esc) Otkaži (Esc) Cancel any current edits (Esc) Otkaži sve tekuće izmene (Esc) @@ -2000,7 +2000,7 @@ Brush preview color Boja pregleda četkice Cache levels Nivoi keša Cache tile size Veličina pločice keša - Camera Raw Defaults Podrazumevana Camera Raw podešavanja + RAW Defaults Podrazumevana RAW podešavanja Canvas border Ivica platna Show canvas dots Prikaži tačke na platnu Clip thumbnails to layer bounds Iseci sličice prema granicama sloja @@ -2087,7 +2087,6 @@ Never Nikad Normal tip Normalan vrh Open as smart object Otvori kao pametni objekat - Open in camera raw Otvori u Camera Raw-u Open documents as tabs Otvaraj dokumente kao kartice Overscroll Pomeranje preko ivice Performance Performanse @@ -2497,8 +2496,6 @@ Roman Hanging Punctuation Viseća interpunkcija za latinicu Avoid Widows/Orphans Izbegavaj udovice/siročiće Compose Slaganje - Adobe Single-line Composer Adobe slagač pojedinačnih redova - Adobe Every-line Composer Adobe slagač svih redova Justification Obostrano poravnanje Word Spacing Razmak između reči Letter Spacing Razmak između slova @@ -2754,7 +2751,6 @@ Intersect with Presek sa Capture Comp Zabeleži kompoziciju No Layer Comps Nema kompozicija slojeva - Adobe PDF Presets… Adobe PDF šabloni… 3D… 3D… Technology Previews… Probne tehnologije… Background from Layer Pozadina od sloja @@ -2845,8 +2841,8 @@ Tone Histogram Tonski histogram Show Selected Region Prikaži izabranu oblast cameraRaw Light Svetlo - Camera Raw Filter ({layer}) Camera Raw filter ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) RAW obrada filter ({layer}) + RAW Develop ({name}) RAW obrada ({name}) cameraRaw Lights Svetli tonovi cameraRaw Darks Tamni tonovi cameraRaw Blacks Crne @@ -3869,8 +3865,8 @@ layerLabel No Color Bez boje Border Obod Box Blur Pravougaono zamućenje Calculations Proračuni - Camera Raw Camera Raw - Camera Raw Filter Camera Raw filter + RAW Develop RAW obrada + RAW Develop Filter RAW obrada filter Channel1 Kanal 1 Channel2 Kanal 2 Channel3 Kanal 3 @@ -4143,7 +4139,7 @@ layerLabel No Color Bez boje Scroll menu down Pomeri meni nadole This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? Ovaj tekstualni sloj mora da se rasterizuje pre nastavka. Njegov tekst više neće moći da se uređuje. Rasterizovati tekst? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Ovaj sloj oblika mora da se rasterizuje pre nastavka. Više neće moći da se uređuje kao oblik. Rasterizovati oblik? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Ovaj pametni objekat mora da se rasterizuje pre nastavka. Njegov sadržaj više neće moći da se uređuje. Rasterizovati pametni objekat? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Ovaj pametni objekat mora da se rasterizuje pre nastavka. Njegov sadržaj više neće moći da se uređuje. Rasterizovati pametni objekat? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Ovaj sloj popune mora da se rasterizuje pre nastavka. Njegov sadržaj popune više neće moći da se uređuje. Rasterizovati sloj? This layer must be rasterized before proceeding. Ovaj sloj mora da se rasterizuje pre nastavka. Color Picker (Background Color) Birač boja (boja pozadine) @@ -4220,7 +4216,6 @@ layerLabel Magenta Magenta Save Path Sačuvaj putanju cameraRaw Highlights Svetla cameraRaw Shadows Senke - All shortcuts reset to Photoshop defaults. Sve prečice su vraćene na podrazumevane vrednosti Photoshop-a. Temporary Privremeno none nijedna red crvena @@ -4270,7 +4265,6 @@ cameraRaw Feather Omekšavanje cameraRaw Midpoint Središte cameraRaw Roundness Zaobljenost cameraRaw Size Veličina - Default Photoshop Size Podrazumevana Photoshop veličina document Orientation Orijentacija Arc Lower Donji luk Arc Upper Gornji luk @@ -4295,8 +4289,8 @@ shape Appearance Izgled Load Settings… Učitaj podešavanja… Save these settings as a Camera Raw .xmp file Sačuvaj ova podešavanja kao Camera Raw .xmp datoteku Load settings from a Camera Raw .xmp file Učitaj podešavanja iz Camera Raw .xmp datoteke - Loaded Camera Raw settings from {file} Camera Raw podešavanja su učitana iz {file} - Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw podešavanja su učitana iz {file} (nije podržano: {n}) + Loaded RAW Develop settings from {file} RAW obrada podešavanja su učitana iz {file} + Loaded RAW Develop settings from {file} ({n} not supported) RAW obrada podešavanja su učitana iz {file} (nije podržano: {n}) Manage submitted jobs in the system print queue Upravljajte poslatim poslovima u sistemskom redu za štampu Pick Color From Image Uzmi boju sa slike Drag to pan · Scroll to zoom · Double-click to fit Prevucite za pomeranje · Skrolujte za zumiranje · Dvaput kliknite za uklapanje @@ -4584,8 +4578,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Skala nijansi sive Current Colors Trenutne boje Make Ramp Web Safe Učini skalu bezbednom za veb + Scroll All Windows Pomeraj sve prozore The path was kept as the Work Path Putanja je sačuvana kao radna putanja The path was discarded Putanja je odbačena +# Art History Brush (#213). Art History Brush Tool Alatka umetnička četkica istorije Tight Short Usko kratko Tight Medium Usko srednje @@ -4672,6 +4668,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Izaberite drugi dokument za svaki kanal. A picked document is no longer open. Jedan izabrani dokument više nije otvoren. A picked document is no longer a grayscale document of the same size. Jedan izabrani dokument više nije dokument u nijansama sive iste veličine. + Netscape Gray Netscape siva # Move tool options bar (#11381) Align top edges Poravnaj gornje ivice Align vertical centers Poravnaj vertikalne centre @@ -4681,7 +4678,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Prikaži granice sloja pri prelasku miša Expand layer group on click Proširi grupu slojeva klikom Show hover bounds from Layers Prikaži granice pri prelasku iz panela Slojevi - Saved Camera Raw settings to {file} Подешавања Camera Raw сачувана у {file} + Saved RAW Develop settings to {file} Подешавања RAW obrada сачувана у {file} Save the settings to each raw's sidecar without opening it Sačuvaj podešavanja u prateću datoteku svakog raw snimka bez otvaranja No settings saved: these raws can't keep a sidecar here Ništa nije sačuvano: ovi raw snimci ovde ne mogu imati prateću datoteku Some settings could not be saved; the raws stay open Neka podešavanja nije moguće sačuvati; raw snimci ostaju otvoreni @@ -4693,3 +4690,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Automatski promeni veličinu platna Keep Relative Position During Layer Reordering Zadrži relativni položaj pri promeni redosleda slojeva Shrinkwrap Canvas on Save Smanji platno na sadržaj pri čuvanju + Move Toolbar to the Right Premesti traku sa alatkama desno + Move Toolbar to the Left Premesti traku sa alatkama levo diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 2157f234de..112a91ca45 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -183,8 +183,8 @@ Trap… Överfyllning… # Layer - Layer via Copy Lager via kopiering - Layer via Cut Lager via urklippning + Layer Via Copy Lager via kopiering + Layer Via Cut Lager via urklippning Duplicate Layer… Duplicera lager… Duplicate… Duplicera… Delete Ta bort @@ -348,7 +348,7 @@ Last Filter Senaste filter Filter Gallery… Filtergalleri… Liquify… Gör flytande… - Camera Raw Filter… Camera Raw-filter… + RAW Develop Filter… RAW-framkallning-filter… Adaptive Wide Angle… Adaptiv vidvinkel… Lens Correction… Objektivkorrigering… Vanishing Point… Fluktpunkt… @@ -873,7 +873,7 @@ Working Black Plate Svart arbetsplåt Working Gray Plate Grå arbetsplåt -# Camera Raw and lens dialogs +# RAW Develop and lens dialogs Basic Grundläggande Detail Detalj HSL/Grayscale HSL/gråskala @@ -903,8 +903,8 @@ Luminance Smoothness Luminansutjämning Vignetting Vinjettering White Balance: As Shot Vitbalans: som tagen - Camera Raw… Camera Raw… - Camera Raw isn't open Camera Raw är inte öppet + RAW Defaults… Standardinställningar för RAW… + RAW Develop isn't open RAW-framkallning är inte öppet Dehaze Ta bort dis Texture Struktur Focal Length Brännvidd @@ -1175,8 +1175,6 @@ Roman Hanging Punctuation Hängande interpunktion (roman) Avoid Widows/Orphans Undvik änkor/horungar Compose Komponera - Adobe Single-line Composer Adobe Single-line Composer - Adobe Every-line Composer Adobe Every-line Composer Justification Marginaljustering Word Spacing Ordavstånd Letter Spacing Teckenavstånd @@ -1758,8 +1756,8 @@ Load Settings… Läs in inställningar… Save these settings as a Camera Raw .xmp file Spara de här inställningarna som en .xmp-fil för Camera Raw Load settings from a Camera Raw .xmp file Läs in inställningar från en Camera Raw .xmp-fil - Loaded Camera Raw settings from {file} Läste in Camera Raw-inställningar från {file} - Loaded Camera Raw settings from {file} ({n} not supported) Läste in Camera Raw-inställningar från {file} ({n} stöds inte) + Loaded RAW Develop settings from {file} Läste in RAW-framkallning-inställningar från {file} + Loaded RAW Develop settings from {file} ({n} not supported) Läste in RAW-framkallning-inställningar från {file} ({n} stöds inte) After (X) Efter (X) Original Original Current Aktuell @@ -2346,7 +2344,7 @@ CPU (no GPU acceleration) CPU (ingen GPU-acceleration) Cache levels Cachenivåer Cache tile size Storlek på cacheblock - Camera Raw Defaults Standardinställningar för Camera Raw + RAW Defaults Standardinställningar för RAW Canvas border Arbetsytans kant Show canvas dots Visa punkter på arbetsytan Clip thumbnails to layer bounds Begränsa miniatyrer till lagergränser @@ -2438,7 +2436,6 @@ Never Aldrig Normal tip Normal spets Open as smart object Öppna som smart objekt - Open in camera raw Öppna i Camera Raw Open documents as tabs Öppna dokument som flikar OpenGL OpenGL Orange Orange @@ -2579,9 +2576,9 @@ Tone Histogram Tonhistogram Show Selected Region Visa markerat område cameraRaw Light Ljus -# Camera Raw: contextual controls and window title - Camera Raw Filter ({layer}) Camera Raw-filter ({layer}) - Camera Raw ({name}) Camera Raw ({name}) +# RAW Develop: contextual controls and window title + RAW Develop Filter ({layer}) RAW-framkallning-filter ({layer}) + RAW Develop ({name}) RAW-framkallning ({name}) Aqua Akvamarin cameraRaw Amount Mängd cameraRaw Blacks Svarta @@ -3386,7 +3383,7 @@ curves Smooth Jämna ut {name} was changed by another app after it was opened or saved here. {name} har ändrats av en annan app efter att den öppnades eller sparades här. Replace it with this document, or cancel and use File › Save As to keep both. Ersätt den med det här dokumentet, eller avbryt och använd Arkiv › Spara som för att behålla båda. -# Dynamic UI labels (fourth pass): filter and adjustment parameters, Camera Raw panels, +# Dynamic UI labels (fourth pass): filter and adjustment parameters, RAW Develop panels, # lighting, History/Layers/paths/channels menus, metadata, System Info, status templates and # dialog text that other catalogs already carry. Written from the meaning of the English labels # in the ordinary Russian graphics-editor vocabulary; no proprietary resource consulted. @@ -3412,13 +3409,11 @@ curves Smooth Jämna ut Adjustment Layers Justeringslager Adjustment Properties Justeringsegenskaper Adjustment layers have nothing to transform Justeringslager har inget att ombilda - Adobe PDF Presets… Adobe PDF-förinställningar… Adobe-rgb-compat Adobe RGB (kompatibel) Adwaita (Dark) Adwaita (mörkt) Adwaita (Light) Adwaita (ljust) After Efter Airbrush: keeps painting while the pointer rests. Airbrush: fortsätter att måla medan pekaren står still. - All shortcuts reset to Photoshop defaults. Alla kortkommandon har återställts till Photoshops standardvärden. Altitude Höjd Ambience Atmosfär Ambient Omgivande @@ -3503,8 +3498,8 @@ curves Smooth Jämna ut Brush Type Penseltyp Burlap Säckväv Calculations Beräkningar - Camera Raw Camera Raw - Camera Raw Filter Camera Raw-filter + RAW Develop RAW-framkallning + RAW Develop Filter RAW-framkallning-filter Cancel transform Avbryt ombildning Candle Light Stearinljus Canvas Size Storlek på arbetsyta @@ -3651,7 +3646,6 @@ curves Smooth Jämna ut Deep Yellow Djupgul Default Foreground and Background Colors Standardfärger för förgrund och bakgrund Default Leaves Standardlöv - Default Photoshop Size Standardstorlek för Photoshop Defaults Standardvärden Define Brush Preset Definiera penselförinställning Define Custom Shape Definiera anpassad form @@ -4491,7 +4485,7 @@ curves Smooth Jämna ut The file could not be saved. Det gick inte att spara filen. Thickness Tjocklek This Layer: Det här lagret: - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Det här smarta objektet måste rasteriseras innan du fortsätter. Innehållet går inte längre att redigera. Vill du rasterisera det smarta objektet? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Det här smarta objektet måste rasteriseras innan du fortsätter. Innehållet går inte längre att redigera. Vill du rasterisera det smarta objektet? This adjustment ({key}) is kept as imported and can't be edited yet. Den här justeringen ({key}) behålls som den importerades och kan inte redigeras ännu. This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Det här fyllningslagret måste rasteriseras innan du fortsätter. Fyllningsinnehållet går inte längre att redigera. Vill du rasterisera lagret? This layer must be rasterized before proceeding. Det här lagret måste rasteriseras innan du fortsätter. @@ -4703,6 +4697,7 @@ shape Appearance Utseende Grayscale Ramp Gråskaleramp Current Colors Aktuella färger Make Ramp Web Safe Gör rampen webbsäker + Scroll All Windows Rulla alla fönster # Art History Brush (#213). Art History Brush Tool Konsthistorikpenselverktyg Tight Short Tät, kort @@ -4751,9 +4746,9 @@ shape Appearance Utseende @plural {n} document|{n} documents {n} dokument|{n} dokument @plural {n} pixel|{n} pixels {n} pixel|{n} pixlar cameraRaw Before (Y) Före (Y) -cameraRaw Camera Raw ({name}) Camera Raw ({name}) -cameraRaw Camera Raw Filter ({layer}) Camera Raw-filter ({layer}) -cameraRaw Camera Raw isn't open Camera Raw är inte öppet +cameraRaw RAW Develop ({name}) RAW-framkallning ({name}) +cameraRaw RAW Develop Filter ({layer}) RAW-framkallning-filter ({layer}) +cameraRaw RAW Develop isn't open RAW-framkallning är inte öppet cameraRaw Cancel Avbryt cameraRaw Canceled opening {name} Öppningen av {name} avbröts cameraRaw Canceled {label} {label} avbröts @@ -4765,7 +4760,7 @@ cameraRaw Highlight Clipping Warning (O) Varning för klippning i högdagrar (O) cameraRaw Highlight Priority Högdagerprioritet cameraRaw Load Settings… Läs in inställningar… cameraRaw Load settings from a Camera Raw .xmp file Läs in inställningar från en Camera Raw .xmp-fil -cameraRaw Loaded Camera Raw settings from {file} Läste in Camera Raw-inställningar från {file} +cameraRaw Loaded RAW Develop settings from {file} Läste in RAW-framkallning-inställningar från {file} cameraRaw Noise Reduction Brusreducering cameraRaw OK OK cameraRaw Open Öppna @@ -4811,6 +4806,7 @@ cameraRaw White Balance: As Shot Vitbalans: som tagen Pick a different document for each channel. Välj ett annat dokument för varje kanal. A picked document is no longer open. Ett av de valda dokumenten är inte längre öppet. A picked document is no longer a grayscale document of the same size. Ett av de valda dokumenten är inte längre ett gråskaledokument i samma storlek. + Netscape Gray Netscape-grå # Move tool options bar (#11381) Align top edges Justera överkanter Align vertical centers Justera vertikala mittpunkter @@ -4827,3 +4823,8 @@ cameraRaw White Balance: As Shot Vitbalans: som tagen Auto-size Canvas Ändra storlek på arbetsytan automatiskt Keep Relative Position During Layer Reordering Behåll relativ position vid ändring av lagerordning Shrinkwrap Canvas on Save Krymp arbetsytan till innehållet vid sparning + Move Toolbar to the Right Flytta verktygsfältet till höger + Move Toolbar to the Left Flytta verktygsfältet till vänster + +# RAW Develop feature labels + Saved RAW Develop settings to {file} RAW-framkallningsinställningar sparade i {file} diff --git a/crates/ui-egui/src/i18n/ta.tsv b/crates/ui-egui/src/i18n/ta.tsv index 3c45b9a218..328cddde41 100644 --- a/crates/ui-egui/src/i18n/ta.tsv +++ b/crates/ui-egui/src/i18n/ta.tsv @@ -219,7 +219,7 @@ Plug-ins… செருகுநிரல்கள்… Type… உரை… Enhanced Controls… மேம்படுத்தப்பட்ட கட்டுப்பாடுகள்… - Camera Raw… கேமரா Raw… + RAW Defaults… RAW இயல்புநிலைகள்… Raw Defaults… Raw இயல்புநிலைகள்… Integrations… ஒருங்கிணைப்புகள்… AI Integrations… AI ஒருங்கிணைப்புகள்… @@ -305,8 +305,8 @@ Artboard… ஆர்ட்போர்டு… Artboard from Group… குழுவிலிருந்து ஆர்ட்போர்டு… Artboard from Layers… அடுக்குகளிலிருந்து ஆர்ட்போர்டு… - Layer via Copy நகல் வழியாக அடுக்கு - Layer via Cut வெட்டு வழியாக அடுக்கு + Layer Via Copy நகல் வழியாக அடுக்கு + Layer Via Cut வெட்டு வழியாக அடுக்கு Layer From Background… பின்னணியிலிருந்து அடுக்கு… Layer from Background… பின்னணியிலிருந்து அடுக்கு… Background from Layer அடுக்கிலிருந்து பின்னணி @@ -548,7 +548,7 @@ Last Filter கடைசி வடிகட்டி Filter Gallery… வடிகட்டி காட்சியகம்… Adaptive Wide Angle… தகவமைக்கும் அகலக் கோணம்… - Camera Raw Filter… கேமரா Raw வடிகட்டி… + RAW Develop Filter… RAW உருவாக்கம் வடிகட்டி… Liquify… திரவமாக்கு… Vanishing Point… மறையும் புள்ளி… Blur மங்கலாக்கு @@ -891,8 +891,8 @@ Load Settings… அமைப்புகளை ஏற்று… Save these settings as a Camera Raw .xmp file இந்த அமைப்புகளை கேமரா Raw .xmp கோப்பாகச் சேமி Load settings from a Camera Raw .xmp file கேமரா Raw .xmp கோப்பிலிருந்து அமைப்புகளை ஏற்று - Loaded Camera Raw settings from {file} {file} இலிருந்து கேமரா Raw அமைப்புகள் ஏற்றப்பட்டன - Loaded Camera Raw settings from {file} ({n} not supported) {file} இலிருந்து கேமரா Raw அமைப்புகள் ஏற்றப்பட்டன ({n} ஆதரிக்கப்படவில்லை) + Loaded RAW Develop settings from {file} {file} இலிருந்து RAW உருவாக்கம் அமைப்புகள் ஏற்றப்பட்டன + Loaded RAW Develop settings from {file} ({n} not supported) {file} இலிருந்து RAW உருவாக்கம் அமைப்புகள் ஏற்றப்பட்டன ({n} ஆதரிக்கப்படவில்லை) Begin recording பதிவைத் தொடங்கு Bend: வளைவு: Bicubic இருபக்கக் கனச்சதுர @@ -920,7 +920,7 @@ Brush Reconstruct Options தூரிகை மறுகட்டமைப்பு விருப்பங்கள் Brush Tool Options தூரிகைக் கருவி விருப்பங்கள் Cache Level: தற்காலிக சேமிப்பு நிலை: - Camera Raw isn't open கேமரா Raw திறக்கப்படவில்லை + RAW Develop isn't open RAW உருவாக்கம் திறக்கப்படவில்லை Cancel ரத்துசெய் Cancel (Esc) ரத்துசெய் (Esc) Manage submitted jobs in the system print queue சமர்ப்பித்த வேலைகளைக் கணினி அச்சு வரிசையில் நிர்வகி @@ -1896,7 +1896,7 @@ Brush preview color தூரிகை முன்னோட்ட நிறம் Cache levels தற்காலிக சேமிப்பு நிலைகள் Cache tile size தற்காலிக சேமிப்பு ஓடு அளவு - Camera Raw Defaults கேமரா Raw இயல்புநிலைகள் + RAW Defaults RAW இயல்புநிலைகள் Canvas border படச்சட்ட விளிம்பு Show canvas dots படச்சட்ட புள்ளிகளைக் காண்பி Clip thumbnails to layer bounds சிறுபடங்களை அடுக்கு எல்லைக்கு வெட்டு @@ -1978,7 +1978,6 @@ Never ஒருபோதும் இல்லை Normal tip இயல்பான முனை Open as smart object திறன்மிகு பொருளாகத் திற - Open in camera raw கேமரா Raw இல் திற Open documents as tabs ஆவணங்களைத் தாவல்களாகத் திற Overscroll மிகைஉருட்டல் Performance செயல்திறன் @@ -2336,8 +2335,8 @@ Tone Histogram தொனி ஹிஸ்டோகிராம் Show Selected Region தேர்ந்தெடுத்த பகுதியைக் காண்பி cameraRaw Light ஒளி - Camera Raw Filter ({layer}) கேமரா Raw வடிகட்டி ({layer}) - Camera Raw ({name}) கேமரா Raw ({name}) + RAW Develop Filter ({layer}) RAW உருவாக்கம் வடிகட்டி ({layer}) + RAW Develop ({name}) RAW உருவாக்கம் ({name}) cameraRaw Lights ஒளிகள் cameraRaw Darks கருமைகள் cameraRaw Red சிவப்பு @@ -2929,8 +2928,6 @@ curves Smooth மென்மையாக்கு Roman Hanging Punctuation ரோமன் தொங்கும் நிறுத்தற்குறிகள் Avoid Widows/Orphans தனித்த வரிகளைத் தவிர் Compose அமை - Adobe Single-line Composer Adobe ஒற்றை வரி அமைப்பி - Adobe Every-line Composer Adobe ஒவ்வொரு வரி அமைப்பி Word Spacing சொல் இடைவெளி Letter Spacing எழுத்து இடைவெளி Glyph Scaling குறியுரு அளவீடு @@ -3126,7 +3123,6 @@ curves Smooth மென்மையாக்கு Intersect with இதனுடன் வெட்டிக்கொள் Capture Comp அமைப்பைப் பதிவுசெய் No Layer Comps அடுக்கு அமைப்புகள் இல்லை - Adobe PDF Presets… Adobe PDF முன்னமைவுகள்… 3D… 3D… Technology Previews… தொழில்நுட்ப முன்னோட்டங்கள்… Add a mask (from the selection; ⌥ inverts) மறைப்பை சேர் (தேர்விலிருந்து; ⌥ தலைகீழாக்கும்) @@ -3752,8 +3748,8 @@ layerLabel No Color நிறம் இல்லை Border எல்லை Box Blur பெட்டி மங்கல் Calculations கணக்கீடுகள் - Camera Raw கேமரா ரா - Camera Raw Filter கேமரா ரா வடிகட்டி + RAW Develop RAW உருவாக்கம் + RAW Develop Filter RAW உருவாக்கம் வடிகட்டி Channel1 சேனல்1 Channel2 சேனல்2 Channel3 சேனல்3 @@ -4027,7 +4023,7 @@ layerLabel No Color நிறம் இல்லை Scroll menu down பட்டியைக் கீழே உருட்டு This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? தொடர்வதற்கு முன் இந்த உரை அடுக்கு ராஸ்டராக்கப்பட வேண்டும். அதன் உரையை இனி திருத்த முடியாது. உரையை ராஸ்டராக்கவா? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? தொடர்வதற்கு முன் இந்த வடிவ அடுக்கு ராஸ்டராக்கப்பட வேண்டும். இதை இனி வடிவமாகத் திருத்த முடியாது. வடிவத்தை ராஸ்டராக்கவா? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? தொடர்வதற்கு முன் இந்த திறன்மிகு பொருள் ராஸ்டராக்கப்பட வேண்டும். அதன் உள்ளடக்கத்தை இனி திருத்த முடியாது. திறன்மிகு பொருளை ராஸ்டராக்கவா? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? தொடர்வதற்கு முன் இந்த திறன்மிகு பொருள் ராஸ்டராக்கப்பட வேண்டும். அதன் உள்ளடக்கத்தை இனி திருத்த முடியாது. திறன்மிகு பொருளை ராஸ்டராக்கவா? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? தொடர்வதற்கு முன் இந்த நிரப்பு அடுக்கு ராஸ்டராக்கப்பட வேண்டும். அதன் நிரப்பு உள்ளடக்கத்தை இனி திருத்த முடியாது. அடுக்கை ராஸ்டராக்கவா? This layer must be rasterized before proceeding. தொடர்வதற்கு முன் இந்த அடுக்கு ராஸ்டராக்கப்பட வேண்டும். Color Picker (Background Color) நிறத் தேர்வி (பின்னணி நிறம்) @@ -4273,3 +4269,8 @@ navigator Zoom பெரிதாக்கல் Transparent (default) ஒளிஊடுருவும் (இயல்புநிலை) The path was kept as the Work Path பாதை பணிப் பாதையாக வைக்கப்பட்டது The path was discarded பாதை நிராகரிக்கப்பட்டது + Move Toolbar to the Right கருவிப்பட்டியை வலப்புறம் நகர்த்து + Move Toolbar to the Left கருவிப்பட்டியை இடப்புறம் நகர்த்து + +# RAW Develop feature labels + Saved RAW Develop settings to {file} RAW உருவாக்க அமைப்புகள் {file} இல் சேமிக்கப்பட்டன diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 36c0c6e3ae..9c6ce98f3d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -13,10 +13,10 @@ const KA: fn() -> Lang = || Lang::from_code("ka").expect("ka registered"); fn hindi_has_the_reveal_and_camera_raw_rows() { assert_eq!(tr(HI(), "Reveal in Explorer"), "Explorer में दिखाएँ"); assert_eq!(tr(HI(), "Reveal in Finder"), "Finder में दिखाएँ"); - assert_eq!(tr(HI(), "Camera Raw…"), "Camera Raw…"); + assert_eq!(tr(HI(), "RAW Defaults…"), "RAW डिफ़ॉल्ट…"); let (rows, errors) = parse_entries(include_str!("hi.tsv")); assert!(errors.is_empty(), "{errors:?}"); - assert!(rows.iter().any(|(ctx, src, _)| ctx.is_empty() && src == "Camera Raw…"), "Camera Raw… is a catalog row, not a fallback"); + assert!(rows.iter().any(|(ctx, src, _)| ctx.is_empty() && src == "RAW Defaults…"), "RAW Defaults… is a catalog row, not a fallback"); } #[test] @@ -568,3 +568,14 @@ fn bundled_catalogs_are_consistent() { } } } + +#[test] +fn raw_develop_labels_are_translated_in_every_shipped_catalog() { + for language in LANGUAGES.iter().skip(1) { + let (entries, errors) = parse_entries(&language.text()); + assert!(errors.is_empty(), "{}: {errors:?}", language.code); + for source in ["RAW Develop", "RAW Develop Filter", "RAW Develop Filter…", "RAW Defaults", "RAW Defaults…"] { + assert!(entries.iter().any(|(_, key, value)| key == source && !value.is_empty()), "{}: {source}", language.code); + } + } +} diff --git a/crates/ui-egui/src/i18n/th.tsv b/crates/ui-egui/src/i18n/th.tsv index ef34287b6b..77b3fedd67 100644 --- a/crates/ui-egui/src/i18n/th.tsv +++ b/crates/ui-egui/src/i18n/th.tsv @@ -176,8 +176,8 @@ Trap… กับดัก… # Layer - Layer via Copy เลเยอร์ผ่านการคัดลอก - Layer via Cut เลเยอร์ผ่านการตัด + Layer Via Copy เลเยอร์ผ่านการคัดลอก + Layer Via Cut เลเยอร์ผ่านการตัด Duplicate Layer… ทำซ้ำเลเยอร์… Duplicate… ทำสำเนา… Delete ลบ @@ -342,7 +342,7 @@ Last Filter ฟิลเตอร์ล่าสุด Filter Gallery… แกลเลอรีฟิลเตอร์… Liquify… ทำให้เหลว… - Camera Raw Filter… ฟิลเตอร์ Camera Raw… + RAW Develop Filter… ฟิลเตอร์ การปรับแต่ง RAW… Adaptive Wide Angle… มุมกว้างแบบปรับได้… Lens Correction… การแก้ไขเลนส์… Vanishing Point… จุดลับสายตา… @@ -861,7 +861,7 @@ Working Black Plate จานดำทำงาน Working Gray Plate แผ่นสีเทาทำงาน -# Camera Raw and lens dialogs +# RAW Develop and lens dialogs Basic ขั้นพื้นฐาน Detail รายละเอียด HSL/Grayscale HSL/ระดับสีเทา @@ -891,8 +891,8 @@ Luminance Smoothness ความนุ่มนวลของความสว่าง Vignetting วิกเนต White Balance: As Shot สมดุลแสงขาว: เท่าที่ถูกถ่าย - Camera Raw… กล้องดิบ… - Camera Raw isn't open Camera Raw ไม่เปิด + RAW Defaults… ค่าเริ่มต้น RAW… + RAW Develop isn't open การปรับแต่ง RAW ไม่เปิด Dehaze ลดหมอกควัน Texture พื้นผิว Focal Length ทางยาวโฟกัส @@ -1163,8 +1163,6 @@ Roman Hanging Punctuation เครื่องหมายวรรคตอนแขวนโรมัน Avoid Widows/Orphans หลีกเลี่ยงแม่ม่าย/เด็กกำพร้า Compose เขียน - Adobe Single-line Composer Adobe นักแต่งเพลงบรรทัดเดียว - Adobe Every-line Composer Adobe นักแต่งเพลงทุกบรรทัด Justification การให้เหตุผล Word Spacing การเว้นวรรคคำ Letter Spacing การเว้นวรรคจดหมาย @@ -1743,8 +1741,8 @@ Load Settings… โหลดการตั้งค่า… Save these settings as a Camera Raw .xmp file บันทึกการตั้งค่าเหล่านี้เป็นไฟล์ Camera Raw .xmp Load settings from a Camera Raw .xmp file โหลดการตั้งค่าจากไฟล์ Camera Raw .xmp - Loaded Camera Raw settings from {file} โหลดการตั้งค่า Camera Raw จาก {file} - Loaded Camera Raw settings from {file} ({n} not supported) โหลดการตั้งค่า Camera Raw จาก {file} (ไม่รองรับ {n}) + Loaded RAW Develop settings from {file} โหลดการตั้งค่า การปรับแต่ง RAW จาก {file} + Loaded RAW Develop settings from {file} ({n} not supported) โหลดการตั้งค่า การปรับแต่ง RAW จาก {file} (ไม่รองรับ {n}) After (X) หลัง (เอ็กซ์) Original ต้นฉบับ Current ปัจจุบัน @@ -2328,7 +2326,7 @@ CPU (no GPU acceleration) CPU (ไม่มีการเร่งความเร็ว GPU) Cache levels ระดับแคช Cache tile size ขนาดไทล์แคช - Camera Raw Defaults ค่าเริ่มต้นCamera Raw + RAW Defaults ค่าเริ่มต้น RAW Canvas border ขอบผ้าใบ Show canvas dots แสดงจุดผ้าใบ Clip thumbnails to layer bounds คลิปภาพขนาดย่อให้เป็นขอบเขตของเลเยอร์ @@ -2415,7 +2413,6 @@ Never ไม่เคย Normal tip ทิปปกติ Open as smart object เปิดเป็นวัตถุอัจฉริยะ - Open in camera raw เปิดในกล้องดิบ Open documents as tabs เปิดเอกสารเป็นแท็บ OpenGL OpenGL Orange ส้ม @@ -2557,9 +2554,9 @@ Tone Histogram โทนฮิสโตแกรม Show Selected Region แสดงภูมิภาคที่เลือก cameraRaw Light เบา -# Camera Raw: contextual controls and window title - Camera Raw Filter ({layer}) ฟิลเตอร์ Camera Raw ({layer}) - Camera Raw ({name}) กล้องดิบ ({name}) +# RAW Develop: contextual controls and window title + RAW Develop Filter ({layer}) ฟิลเตอร์ การปรับแต่ง RAW ({layer}) + RAW Develop ({name}) การปรับแต่ง RAW ({name}) Aqua อควา cameraRaw Amount จำนวน cameraRaw Blacks คนผิวดำ @@ -3367,7 +3364,7 @@ curves Smooth เรียบเนียน {name} was changed by another app after it was opened or saved here. {name} ถูกเปลี่ยนโดยแอปอื่นหลังจากเปิดหรือบันทึกที่นี่ Replace it with this document, or cancel and use File › Save As to keep both. แทนที่ด้วยเอกสารนี้ หรือยกเลิกและใช้ไฟล์ › บันทึกเป็นเพื่อเก็บทั้งสองอย่าง -# Dynamic UI labels (fourth pass): filter and adjustment parameters, Camera Raw panels, +# Dynamic UI labels (fourth pass): filter and adjustment parameters, RAW Develop panels, # lighting, History/Layers/paths/channels menus, metadata, System Info, status templates and # dialog text that other catalogs already carry. Written from the meaning of the English labels # in the ordinary Russian graphics-editor vocabulary; no proprietary resource consulted. @@ -3393,13 +3390,11 @@ curves Smooth เรียบเนียน Adjustment Layers เลเยอร์ปรับแต่ง Adjustment Properties คุณสมบัติการปรับ Adjustment layers have nothing to transform เลเยอร์การปรับแต่งไม่มีอะไรจะเปลี่ยนแปลง - Adobe PDF Presets… ค่าที่ตั้งล่วงหน้า Adobe PDF… Adobe-rgb-compat Adobe-rgb-compat Adwaita (Dark) แอดเวตา (ความมืด) Adwaita (Light) อัดเวตา (ธาตุเบา) After หลังจากนั้น Airbrush: keeps painting while the pointer rests. พู่กัน: คงการวาดภาพในขณะที่ตัวชี้วางอยู่ - All shortcuts reset to Photoshop defaults. ทางลัดทั้งหมดรีเซ็ตเป็นค่าเริ่มต้นของ Photoshop Altitude ระดับความสูง Ambience บรรยากาศ Ambient สิ่งแวดล้อม @@ -3484,8 +3479,8 @@ curves Smooth เรียบเนียน Brush Type ประเภทแปรง Burlap ผ้ากระสอบ Calculations การคำนวณ - Camera Raw กล้องดิบ - Camera Raw Filter ฟิลเตอร์ Camera Raw + RAW Develop การปรับแต่ง RAW + RAW Develop Filter ฟิลเตอร์ การปรับแต่ง RAW Cancel transform ยกเลิกการแปลง Candle Light แสงเทียน Canvas Size ขนาดผ้าใบ @@ -3632,7 +3627,6 @@ curves Smooth เรียบเนียน Deep Yellow สีเหลืองเข้ม Default Foreground and Background Colors สีพื้นหน้าและพื้นหลังเริ่มต้น Default Leaves ใบเริ่มต้น - Default Photoshop Size ขนาด Photoshop เริ่มต้น Defaults ค่าเริ่มต้น Define Brush Preset กำหนดพรีเซ็ตแปรง Define Custom Shape กำหนดรูปร่างที่กำหนดเอง @@ -4472,7 +4466,7 @@ curves Smooth เรียบเนียน The file could not be saved. ไม่สามารถบันทึกไฟล์ได้ Thickness ความหนา This Layer: เลเยอร์นี้: - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? สมาร์ทออบเจ็กต์นี้ต้องได้รับการแรสเตอร์ก่อนดำเนินการต่อ เนื้อหาจะไม่สามารถแก้ไขได้อีกต่อไป แรสเตอร์วัตถุอัจฉริยะหรือไม่ + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? สมาร์ทออบเจ็กต์นี้ต้องได้รับการแรสเตอร์ก่อนดำเนินการต่อ เนื้อหาจะไม่สามารถแก้ไขได้อีกต่อไป แรสเตอร์วัตถุอัจฉริยะหรือไม่ This adjustment ({key}) is kept as imported and can't be edited yet. การปรับเปลี่ยนนี้ ({key}) ถูกเก็บไว้เป็นการนำเข้าและยังไม่สามารถแก้ไขได้ This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? เลเยอร์เติมนี้จะต้องถูกแรสเตอร์ก่อนดำเนินการต่อ เนื้อหาที่กรอกจะไม่สามารถแก้ไขได้อีกต่อไป แรสเตอร์เลเยอร์หรือไม่? This layer must be rasterized before proceeding. เลเยอร์นี้จะต้องถูกแรสเตอร์ก่อนดำเนินการต่อ @@ -4735,9 +4729,9 @@ shape Appearance ลักษณะที่ปรากฏ @plural {n} document|{n} documents {n} เอกสาร @plural {n} pixel|{n} pixels {n} พิกเซล cameraRaw Before (Y) ก่อน (ญ) -cameraRaw Camera Raw ({name}) กล้องดิบ ({name}) -cameraRaw Camera Raw Filter ({layer}) ฟิลเตอร์ Camera Raw ({layer}) -cameraRaw Camera Raw isn't open Camera Raw ไม่เปิด +cameraRaw RAW Develop ({name}) การปรับแต่ง RAW ({name}) +cameraRaw RAW Develop Filter ({layer}) ฟิลเตอร์ การปรับแต่ง RAW ({layer}) +cameraRaw RAW Develop isn't open การปรับแต่ง RAW ไม่เปิด cameraRaw Cancel ยกเลิก cameraRaw Cancelled opening {name} ยกเลิกการเปิด {name} cameraRaw Cancelled {label} ยกเลิก {label} @@ -4749,7 +4743,7 @@ cameraRaw Highlight Clipping Warning (O) คำเตือนการตัด cameraRaw Highlight Priority เน้นลำดับความสำคัญ cameraRaw Load Settings… โหลดการตั้งค่า… cameraRaw Load settings from a Camera Raw .xmp file โหลดการตั้งค่าจากไฟล์ Camera Raw .xmp -cameraRaw Loaded Camera Raw settings from {file} โหลดการตั้งค่า Camera Raw จาก {file} +cameraRaw Loaded RAW Develop settings from {file} โหลดการตั้งค่า การปรับแต่ง RAW จาก {file} cameraRaw Noise Reduction ลดเสียงรบกวน cameraRaw OK ตกลง cameraRaw Open เปิด @@ -4773,3 +4767,8 @@ cameraRaw White Balance: As Shot สมดุลแสงขาว: เท่า Transparent (default) โปร่งใส (ค่าเริ่มต้น) The path was kept as the Work Path เก็บเส้นทางไว้เป็นเส้นทางการทำงานแล้ว The path was discarded ทิ้งเส้นทางแล้ว + Move Toolbar to the Right ย้ายแถบเครื่องมือไปทางขวา + Move Toolbar to the Left ย้ายแถบเครื่องมือไปทางซ้าย + +# RAW Develop feature labels + Saved RAW Develop settings to {file} บันทึกการตั้งค่าการปรับแต่ง RAW ไปยัง {file} แล้ว diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ee2567d21e..80cb929d78 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -251,7 +251,7 @@ Plugins… Eklentiler… Type… Metin… Enhanced Controls… Gelişmiş Kontroller… - Camera Raw… Camera Raw… + RAW Defaults… RAW Varsayılanları… Raw Defaults… Ham Varsayılanlar… Integrations… Entegrasyonlar… AI Integrations… Yapay Zeka Entegrasyonları… @@ -339,8 +339,8 @@ Artboard… Çalışma Yüzeyi… Artboard from Group… Gruptan Çalışma Yüzeyi… Artboard from Layers… Katmanlardan Çalışma Yüzeyi… - Layer via Copy Kopyalama Yoluyla Katman - Layer via Cut Kesim Yoluyla Katman + Layer Via Copy Kopyalama Yoluyla Katman + Layer Via Cut Kesim Yoluyla Katman Layer From Background… Arka Plandan Katman… Layer from Background… Arka Plandan Katman… Background From Layer Katmandan Arka Plan @@ -582,7 +582,7 @@ Last Filter Son Filtre Filter Gallery… Filtre Galerisi… Adaptive Wide Angle… Uyarlanabilir Geniş Açı… - Camera Raw Filter… Camera Raw Filtresi… + RAW Develop Filter… RAW Geliştirme Filtresi… Liquify… Sıvılaştır… Vanishing Point… Ufuk Noktası… Blur Bulanıklaştırma @@ -948,7 +948,7 @@ Brush Reconstruct Options Fırçayla Yeniden Yapılandırma Seçenekleri Brush Tool Options Fırça Aracı Seçenekleri Cache Level: Önbellek Düzeyi: - Camera Raw isn't open Camera Raw açık değil + RAW Develop isn't open RAW Geliştirme açık değil Cancel İptal Reset Sıfırla Cancel (Esc) İptal (Esc) @@ -1914,7 +1914,7 @@ Brush preview color Fırça önizleme rengi Cache levels Önbellek düzeyleri Cache tile size Önbellek kutucuğu boyutu - Camera Raw Defaults Camera Raw Varsayılanları + RAW Defaults RAW Varsayılanları Canvas border Tuval kenarlığı Show canvas dots Tuval noktalarını göster Clip thumbnails to layer bounds Küçük resimleri katman sınırlarına kırp @@ -2001,7 +2001,6 @@ Never Asla Normal tip Normal uç Open as smart object Akıllı nesne olarak aç - Open in camera raw Camera raw'da aç Open documents as tabs Belgeleri sekmeler halinde aç Overscroll Aşırı kaydırma Performance Performans @@ -2352,8 +2351,8 @@ 3 x 3 3 x 3 4 x 4 4 x 4 5 x 5 5 x 5 - Camera Raw Filter ({layer}) Camera Raw Filtresi ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) RAW Geliştirme Filtresi ({layer}) + RAW Develop ({name}) RAW Geliştirme ({name}) Edit Type Metni Düzenle Grid: Izgara: Highlight Clipping Warning (O) Parlak Ton Kırpma Uyarısı (O) @@ -3354,7 +3353,6 @@ cameraRaw Color Renk Add Pins Pim Ekle Add a mask (from the selection; ⌥ inverts) Bir maske ekleyin (seçimden; ⌥ tersine çevirir) Adds grain to the soft edges of the brush tip. Fırça ucunun yumuşak kenarlarına gren ekler. - Adobe PDF Presets… Adobe PDF Ön Ayarları… Advanced Blending Gelişmiş Karıştırma After (X) Sonra (X) Airbrush: keeps painting while the pointer rests. Airbrush: İşaretçi dururken boyamaya devam eder. @@ -3381,8 +3379,8 @@ cameraRaw Color Renk Border Kenarlık Box Blur Kutu Bulanıklığı Calculations Hesaplamalar - Camera Raw Camera Raw - Camera Raw Filter Camera Raw Filtresi + RAW Develop RAW Geliştirme + RAW Develop Filter RAW Geliştirme Filtresi Canvas rotation Tuval döndürme Channel1 Kanal 1 Channel2 Kanal 2 @@ -3665,8 +3663,6 @@ cameraRaw Whites Beyazlar Mac Crisp Mac Net Mac Strong Mac Güçlü Mac Smooth Mac Yumuşak - Adobe Single-line Composer Adobe Tek Satırlı Dizgi Motoru - Adobe Every-line Composer Adobe Tüm Satırlı Dizgi Motoru X X Y Y 30 fps 30 fps @@ -4002,8 +3998,8 @@ cameraData Lens Lens Load Settings… Ayarları Yükle… Save these settings as a Camera Raw .xmp file Bu ayarları Camera Raw .xmp dosyası olarak kaydet Load settings from a Camera Raw .xmp file Ayarları bir Camera Raw .xmp dosyasından yükle - Loaded Camera Raw settings from {file} Camera Raw ayarları {file} dosyasından yüklendi - Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw ayarları {file} dosyasından yüklendi ({n} desteklenmiyor) + Loaded RAW Develop settings from {file} RAW Geliştirme ayarları {file} dosyasından yüklendi + Loaded RAW Develop settings from {file} ({n} not supported) RAW Geliştirme ayarları {file} dosyasından yüklendi ({n} desteklenmiyor) Auto Add/Delete Otomatik Ekle/Sil Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Yazdırma Ayarlarında ayrıca Ayna Görüntüsünü açmayın: iki yansıtma birbirini iptal eder. Print Settings… Yazdırma Ayarları… @@ -4237,8 +4233,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Gri Tonlama Şeridi Current Colors Geçerli Renkler Make Ramp Web Safe Şeridi Web Renkleriyle Sınırla + Scroll All Windows Tüm Pencereleri Kaydır The path was kept as the Work Path Yol, Çalışma Yolu olarak korundu The path was discarded Yol atıldı +# Art History Brush (#213). Art History Brush Tool Sanat Tarihi Fırçası Aracı Tight Short Sıkı Kısa Tight Medium Sıkı Orta @@ -4337,6 +4335,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Her kanal için farklı bir belge seçin. A picked document is no longer open. Seçilen belgelerden biri artık açık değil. A picked document is no longer a grayscale document of the same size. Seçilen belgelerden biri artık aynı boyutta gri tonlamalı bir belge değil. + Netscape Gray Netscape Grisi # Move tool options bar (#11381) Align top edges Üst kenarları hizala Align vertical centers Dikey merkezleri hizala @@ -4346,7 +4345,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Üzerine gelince katman sınırlarını göster Expand layer group on click Tıklayınca katman grubunu genişlet Show hover bounds from Layers Katmanlar'dan üzerine gelme sınırlarını göster - Saved Camera Raw settings to {file} Camera Raw ayarları {file} dosyasına kaydedildi + Saved RAW Develop settings to {file} RAW Geliştirme ayarları {file} dosyasına kaydedildi Save the settings to each raw's sidecar without opening it Ayarları her raw dosyasının yan dosyasına kaydet, açmadan No settings saved: these raws can't keep a sidecar here Hiçbir şey kaydedilmedi: bu raw dosyaları burada yan dosyaya sahip olamaz Some settings could not be saved; the raws stay open Bazı ayarlar kaydedilemedi; raw dosyaları açık kalıyor @@ -4358,3 +4357,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Tuvali Otomatik Boyutlandır Keep Relative Position During Layer Reordering Katmanları Yeniden Sıralarken Göreli Konumu Koru Shrinkwrap Canvas on Save Kaydederken Tuvali İçeriğe Göre Küçült + Move Toolbar to the Right Araç çubuğunu sağa taşı + Move Toolbar to the Left Araç çubuğunu sola taşı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8035a7f224..ef8def435f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -57,7 +57,7 @@ # Filters and adjustments dialogs -# Camera Raw and lens dialogs +# RAW Develop and lens dialogs # Adjustments panel @@ -116,7 +116,7 @@ # Preference dialog: generated setting labels and dropdown choices # Rendering mode and recovery -# Camera Raw: contextual controls and window title +# RAW Develop: contextual controls and window title @@ -348,8 +348,8 @@ Duotone… Дуплекс… Duotone Дуплекс Trap… Трепінг… - Layer via Copy Шар через копіювання - Layer via Cut Шар через вирізання + Layer Via Copy Шар через копіювання + Layer Via Cut Шар через вирізання Duplicate Layer… Дублювати шар… Duplicate… Дублювати… Delete Видалити @@ -494,7 +494,7 @@ Last Filter Останній фільтр Filter Gallery… Галерея фільтрів… Liquify… Пластика… - Camera Raw Filter… Фільтр Camera Raw… + RAW Develop Filter… Фільтр Обробка RAW… Adaptive Wide Angle… Адаптивний широкий кут… Lens Correction… Корекція об'єктива… Vanishing Point… Точка сходження… @@ -1026,8 +1026,8 @@ Luminance Smoothness Плавність яскравості Vignetting Віньєтування White Balance: As Shot Баланс білого: як під час знімання - Camera Raw… Camera Raw… - Camera Raw isn't open Camera Raw не відкрито + RAW Defaults… Типові параметри RAW… + RAW Develop isn't open Обробка RAW не відкрито Dehaze Усунення серпанку Texture Текстура Focal Length Фокусна відстань @@ -1283,8 +1283,6 @@ Roman Hanging Punctuation Висяча латинська пунктуація Avoid Widows/Orphans Уникати висячих рядків Compose Компонування - Adobe Single-line Composer Однорядковий компонувальник Adobe - Adobe Every-line Composer Багаторядковий компонувальник Adobe Justification Вирівнювання по ширині Word Spacing Інтервал між словами Letter Spacing Інтервал між літерами @@ -1842,8 +1840,8 @@ Load Settings… Завантажити налаштування… Save these settings as a Camera Raw .xmp file Зберегти ці налаштування у файл Camera Raw .xmp Load settings from a Camera Raw .xmp file Завантажити налаштування з файлу Camera Raw .xmp - Loaded Camera Raw settings from {file} Налаштування Camera Raw завантажено з {file} - Loaded Camera Raw settings from {file} ({n} not supported) Налаштування Camera Raw завантажено з {file} (не підтримується: {n}) + Loaded RAW Develop settings from {file} Налаштування Обробка RAW завантажено з {file} + Loaded RAW Develop settings from {file} ({n} not supported) Налаштування Обробка RAW завантажено з {file} (не підтримується: {n}) After (X) Після (X) Original Оригінал Current Поточний @@ -2409,7 +2407,7 @@ CPU (no GPU acceleration) CPU (без прискорення GPU) Cache levels Рівні кешу Cache tile size Розмір плитки кешу - Camera Raw Defaults Типові параметри Camera Raw + RAW Defaults Типові параметри RAW Canvas border Межа полотна Show canvas dots Показувати крапки полотна Clip thumbnails to layer bounds Обрізати мініатюри до меж шару @@ -2501,7 +2499,6 @@ Never Ніколи Normal tip Звичайний кінчик Open as smart object Відкривати як смартоб'єкт - Open in camera raw Відкривати в Camera Raw Open documents as tabs Відкривати документи у вкладках OpenGL OpenGL Orange Оранжевий @@ -2639,8 +2636,8 @@ Tone Histogram Тонова гістограма Show Selected Region Показувати вибрану область cameraRaw Light Світло - Camera Raw Filter ({layer}) Фільтр Camera Raw ({layer}) - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop Filter ({layer}) Фільтр Обробка RAW ({layer}) + RAW Develop ({name}) Обробка RAW ({name}) Aqua Аквамариновий cameraRaw Amount Величина cameraRaw Blacks Чорні тони @@ -3365,7 +3362,7 @@ cameraRaw Masking Маскування Color Settings Налаштування кольору Assign Profile Призначити профіль Convert to Profile Перетворити на профіль - Camera Raw Camera Raw + RAW Develop Обробка RAW Raw Defaults Типові параметри Raw AI Integrations Інтеграції ШІ Install Plug-in Установити плагін @@ -3412,7 +3409,7 @@ cameraRaw Masking Маскування Border Межа Contract Стиснути Filter Gallery Галерея фільтрів - Camera Raw Filter Фільтр Camera Raw + RAW Develop Filter Фільтр Обробка RAW Liquify Пластика Vanishing Point Точка сходження Field Blur Розмиття поля @@ -3652,7 +3649,6 @@ cameraRaw Masking Маскування @id filter.sharpen.sharpen Підвищити різкість Good Добра Best Найкраща - Adobe PDF Presets… Набори Adobe PDF… 3D… 3D… Technology Previews… Попередній перегляд технологій… Background from Layer Фон із шару @@ -4157,7 +4153,7 @@ curves Smooth Згладити Color Picker (Custom Canvas Color) Вибір кольору (власний колір полотна) This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? Щоб продовжити, потрібно растеризувати цей текстовий шар. Після цього його текст більше не можна буде редагувати. Растеризувати текст? This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? Щоб продовжити, потрібно растеризувати цей шар фігури. Після цього його більше не можна буде редагувати як фігуру. Растеризувати фігуру? - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? Щоб продовжити, потрібно растеризувати цей смартоб’єкт. Після цього його вміст більше не можна буде редагувати. Растеризувати смартоб’єкт? + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? Щоб продовжити, потрібно растеризувати цей смартоб’єкт. Після цього його вміст більше не можна буде редагувати. Растеризувати смартоб’єкт? This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? Щоб продовжити, потрібно растеризувати цей шар заливки. Після цього його заливку більше не можна буде редагувати. Растеризувати шар? Demosaic Демозаїк How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with. Як відновлюється мозаїка кольорового фільтра камери. Застосовується під час відкриття файлу; попередній перегляд показує метод, з яким файл було відкрито. @@ -4218,8 +4214,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Шкала градацій сірого Current Colors Поточні кольори Make Ramp Web Safe Зробити шкалу безпечною для вебу + Scroll All Windows Прокручувати всі вікна The path was kept as the Work Path Контур збережено як робочий контур The path was discarded Контур видалено +# Art History Brush (#213). Art History Brush Tool Інструмент «Художній пензель історії» Tight Short Щільний короткий Tight Medium Щільний середній @@ -4317,6 +4315,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Виберіть окремий документ для кожного каналу. A picked document is no longer open. Один із вибраних документів більше не відкрито. A picked document is no longer a grayscale document of the same size. Один із вибраних документів більше не є документом у градаціях сірого того самого розміру. + Netscape Gray Сірий Netscape # Move tool options bar (#11381) Align top edges Вирівняти верхні краї Align vertical centers Вирівняти центри по вертикалі @@ -4326,7 +4325,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Показувати межі шару під час наведення Expand layer group on click Розгортати групу шарів за клацанням Show hover bounds from Layers Показувати межі під час наведення з панелі «Шари» - Saved Camera Raw settings to {file} Налаштування Camera Raw збережено в {file} + Saved RAW Develop settings to {file} Налаштування Обробка RAW збережено в {file} Save the settings to each raw's sidecar without opening it Зберегти налаштування в супровідний файл кожного raw, не відкриваючи його No settings saved: these raws can't keep a sidecar here Нічого не збережено: ці raw тут не можуть мати супровідного файлу Some settings could not be saved; the raws stay open Не вдалося зберегти деякі налаштування; raw залишаються відкритими @@ -4338,3 +4337,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Автоматично змінювати розмір полотна Keep Relative Position During Layer Reordering Зберігати відносне положення під час зміни порядку шарів Shrinkwrap Canvas on Save Зменшувати полотно до вмісту під час збереження + Move Toolbar to the Right Перемістити панель інструментів праворуч + Move Toolbar to the Left Перемістити панель інструментів ліворуч diff --git a/crates/ui-egui/src/i18n/ur.tsv b/crates/ui-egui/src/i18n/ur.tsv index 4d5eaf7961..2851d7d070 100644 --- a/crates/ui-egui/src/i18n/ur.tsv +++ b/crates/ui-egui/src/i18n/ur.tsv @@ -224,7 +224,7 @@ Plug-ins… پلگ انز… Type… متن… Enhanced Controls… بہتر کنٹرولز… - Camera Raw… کیمرہ را… + RAW Defaults… RAW ڈیفالٹس… Raw Defaults… را ڈیفالٹس… Integrations… انضمام… AI Integrations… AI انضمام… @@ -311,8 +311,8 @@ Artboard… آرٹ بورڈ… Artboard from Group… گروپ سے آرٹ بورڈ… Artboard from Layers… تہوں سے آرٹ بورڈ… - Layer via Copy کاپی کے ذریعے تہہ - Layer via Cut کٹ کے ذریعے تہہ + Layer Via Copy کاپی کے ذریعے تہہ + Layer Via Cut کٹ کے ذریعے تہہ Layer From Background… پس منظر سے تہہ… Layer from Background… پس منظر سے تہہ… Background from Layer تہہ سے پس منظر @@ -554,7 +554,7 @@ Last Filter آخری فلٹر Filter Gallery… فلٹر گیلری… Adaptive Wide Angle… اڈاپٹیو وائیڈ اینگل… - Camera Raw Filter… کیمرہ را فلٹر… + RAW Develop Filter… RAW ڈیولپمنٹ فلٹر… Liquify… لیکویفائی… Vanishing Point… وینشنگ پوائنٹ… Blur دھندلا پن @@ -902,8 +902,8 @@ Load Settings… ترتیبات لوڈ کریں… Save these settings as a Camera Raw .xmp file ان ترتیبات کو کیمرہ را .xmp فائل کے طور پر محفوظ کریں Load settings from a Camera Raw .xmp file کیمرہ را .xmp فائل سے ترتیبات لوڈ کریں - Loaded Camera Raw settings from {file} {file} سے کیمرہ را ترتیبات لوڈ ہو گئیں - Loaded Camera Raw settings from {file} ({n} not supported) {file} سے کیمرہ را ترتیبات لوڈ ہو گئیں ({n} سپورٹڈ نہیں) + Loaded RAW Develop settings from {file} {file} سے RAW ڈیولپمنٹ ترتیبات لوڈ ہو گئیں + Loaded RAW Develop settings from {file} ({n} not supported) {file} سے RAW ڈیولپمنٹ ترتیبات لوڈ ہو گئیں ({n} سپورٹڈ نہیں) Begin recording ریکارڈنگ شروع کریں Bend: موڑ: Bicubic بائی کیوبک @@ -931,7 +931,7 @@ Brush Reconstruct Options برش ری کنسٹرکٹ کے اختیارات Brush Tool Options برش ٹول کے اختیارات Cache Level: کیشے لیول: - Camera Raw isn't open کیمرہ را کھلا نہیں ہے + RAW Develop isn't open RAW ڈیولپمنٹ کھلا نہیں ہے Cancel منسوخ کریں Cancel (Esc) منسوخ کریں (Esc) Manage submitted jobs in the system print queue سسٹم پرنٹ قطار میں جمع شدہ کام منظم کریں @@ -1902,7 +1902,7 @@ Brush preview color برش پیش منظر کا رنگ Cache levels کیشے لیولز Cache tile size کیشے ٹائل حجم - Camera Raw Defaults کیمرہ را ڈیفالٹس + RAW Defaults RAW ڈیفالٹس Canvas border کینوس بارڈر Show canvas dots کینوس نقطے دکھائیں Clip thumbnails to layer bounds تھمب نیلز کو تہہ کی حدود میں کلپ کریں @@ -1984,7 +1984,6 @@ Never کبھی نہیں Normal tip نارمل ٹپ Open as smart object سمارٹ آبجیکٹ کے طور پر کھولیں - Open in camera raw کیمرہ را میں کھولیں Open documents as tabs دستاویزات کو ٹیبز کے طور پر کھولیں Overscroll اوور اسکرول Performance کارکردگی @@ -2345,8 +2344,8 @@ Tone Histogram ٹون ہسٹوگرام Show Selected Region منتخب خطہ دکھائیں cameraRaw Light روشنی - Camera Raw Filter ({layer}) کیمرہ را فلٹر ({layer}) - Camera Raw ({name}) کیمرہ را ({name}) + RAW Develop Filter ({layer}) RAW ڈیولپمنٹ فلٹر ({layer}) + RAW Develop ({name}) RAW ڈیولپمنٹ ({name}) cameraRaw Lights روشن حصے cameraRaw Darks تاریک حصے cameraRaw Red سرخ @@ -2943,8 +2942,6 @@ curves Smooth ہموار Roman Hanging Punctuation رومن ہینگنگ رموز اوقاف Avoid Widows/Orphans ودوز/اورفنز سے گریز کریں Compose کمپوز کریں - Adobe Single-line Composer Adobe سنگل لائن کمپوزر - Adobe Every-line Composer Adobe ایوری لائن کمپوزر Word Spacing لفظ کا وقفہ Letter Spacing حرف کا وقفہ Glyph Scaling گلف اسکیلنگ @@ -3140,7 +3137,6 @@ curves Smooth ہموار Intersect with کے ساتھ جوڑیں Capture Comp کمپوزیشن قبضہ کریں No Layer Comps کوئی تہہ کمپوزیشن نہیں - Adobe PDF Presets… Adobe PDF پری سیٹس… 3D… 3D… Technology Previews… ٹیکنالوجی پیش منظر… Add a mask (from the selection; ⌥ inverts) ماسک شامل کریں (انتخاب سے؛ ⌥ الٹ دیتا ہے) @@ -3757,8 +3753,8 @@ layerLabel No Color بلا رنگ Border بارڈر Box Blur باکس دھندلاپن Calculations حسابات - Camera Raw کیمرہ را - Camera Raw Filter کیمرہ را فلٹر + RAW Develop RAW ڈیولپمنٹ + RAW Develop Filter RAW ڈیولپمنٹ فلٹر Channel1 چینل1 Channel2 چینل2 Channel3 چینل3 @@ -4018,7 +4014,7 @@ layerLabel No Color بلا رنگ Scroll menu down مینیو نیچے اسکرول کریں This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type? آگے بڑھنے سے پہلے اس متن تہہ کو ریسٹرائز کرنا ضروری ہے۔ اس کا متن مزید قابل ترمیم نہیں رہے گا۔ کیا قسم کو ریسٹرائز کریں؟ This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape? آگے بڑھنے سے پہلے اس شکل تہہ کو ریسٹرائز کرنا ضروری ہے۔ یہ مزید شکل کے طور پر قابل ترمیم نہیں رہے گی۔ کیا شکل کو ریسٹرائز کریں؟ - This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object? آگے بڑھنے سے پہلے اس سمارٹ آبجیکٹ کو ریسٹرائز کرنا ضروری ہے۔ اس کا مواد مزید قابل ترمیم نہیں رہے گا۔ کیا سمارٹ آبجیکٹ کو ریسٹرائز کریں؟ + This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object? آگے بڑھنے سے پہلے اس سمارٹ آبجیکٹ کو ریسٹرائز کرنا ضروری ہے۔ اس کا مواد مزید قابل ترمیم نہیں رہے گا۔ کیا سمارٹ آبجیکٹ کو ریسٹرائز کریں؟ This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer? آگے بڑھنے سے پہلے اس بھرائی تہہ کو ریسٹرائز کرنا ضروری ہے۔ اس کا بھرائی مواد مزید قابل ترمیم نہیں رہے گا۔ کیا تہہ کو ریسٹرائز کریں؟ This layer must be rasterized before proceeding. آگے بڑھنے سے پہلے اس تہہ کو ریسٹرائز کرنا ضروری ہے۔ Color Picker (Background Color) رنگ چنندہ (پس منظر کا رنگ) @@ -4572,3 +4568,8 @@ navigator Zoom زوم @plural {n} action file loaded|{n} action files loaded {n} ایکشن فائل لوڈ ہوئی|{n} ایکشن فائلیں لوڈ ہوئیں @plural {n} file could not be loaded: {errors}|{n} files could not be loaded: {errors} {n} فائل لوڈ نہیں ہو سکی: {errors}|{n} فائلیں لوڈ نہیں ہو سکیں: {errors} @plural {what}: {n} Image Assets output failed|{what}: {n} Image Assets outputs failed {what}: {n} تصویری اثاثہ آؤٹ پٹ ناکام ہوا|{what}: {n} تصویری اثاثے آؤٹ پٹس ناکام ہوئے + Move Toolbar to the Right ٹول بار کو دائیں منتقل کریں + Move Toolbar to the Left ٹول بار کو بائیں منتقل کریں + +# RAW Develop feature labels + Saved RAW Develop settings to {file} RAW ڈیولپمنٹ کی ترتیبات {file} میں محفوظ ہو گئیں diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f1e4723709..00cde2af6c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -62,7 +62,7 @@ # Mixer Brush (required for every registered non-English language) -# Camera Raw labels (required for every registered non-English language) +# RAW Develop labels (required for every registered non-English language) # Phase 4.1 — Preferences dialog @@ -75,13 +75,13 @@ # Phase 4.5 — Preset Manager + Export/Import Presets -# Phase 4.6 — Camera Raw chrome + Light/Color basics (tone, WB, presence) +# Phase 4.6 — RAW Develop chrome + Light/Color basics (tone, WB, presence) -# Phase 4.7 — Camera Raw Curve + Color Mixer +# Phase 4.7 — RAW Develop Curve + Color Mixer -# Phase 4.8 — Camera Raw Color Grading + Detail +# Phase 4.8 — RAW Develop Color Grading + Detail -# Phase 4.10 — Camera Raw Effects (Texture/Clarity/Dehaze + Vignetting + Grain) +# Phase 4.10 — RAW Develop Effects (Texture/Clarity/Dehaze + Vignetting + Grain) # Phase 4.13 — New Document + Home + Image Size @@ -289,7 +289,7 @@ Puppet Warp Biến dạng con rối Purge Dọn Quick Export as PNG Xuất nhanh dạng PNG - Raw Defaults… Mặc định Camera Raw… + Raw Defaults… Mặc định RAW… Redo Làm lại Remove Warp Split Gỡ tách biến dạng Render Video… Xuất video… @@ -458,8 +458,8 @@ Layer from Background… Lớp từ nền… Layer Mask Mặt nạ lớp Layer Style Kiểu lớp - Layer via Copy Lớp bằng sao chép - Layer via Cut Lớp bằng cắt + Layer Via Copy Lớp bằng sao chép + Layer Via Cut Lớp bằng cắt Layer… Lớp… Left Edges Cạnh trái Levels… Mức… @@ -630,7 +630,7 @@ Blur Gallery Thư viện làm mờ Blur More Làm mờ thêm Box Blur… Làm mờ hộp… - Camera Raw Filter… Bộ lọc Camera Raw… + RAW Develop Filter… Bộ lọc Xử lý RAW… Clouds Mây Color Halftone… Bán tông màu… Convert for Smart Filters Chuyển cho bộ lọc thông minh @@ -1449,13 +1449,13 @@ Load Settings… Tải cài đặt… Save these settings as a Camera Raw .xmp file Lưu các cài đặt này thành tệp .xmp Camera Raw Load settings from a Camera Raw .xmp file Tải cài đặt từ tệp .xmp Camera Raw - Loaded Camera Raw settings from {file} Đã tải cài đặt Camera Raw từ {file} - Loaded Camera Raw settings from {file} ({n} not supported) Đã tải cài đặt Camera Raw từ {file} ({n} không được hỗ trợ) + Loaded RAW Develop settings from {file} Đã tải cài đặt Xử lý RAW từ {file} + Loaded RAW Develop settings from {file} ({n} not supported) Đã tải cài đặt Xử lý RAW từ {file} ({n} không được hỗ trợ) Blacks Điểm đen Blending Pha trộn Blue Xanh dương - Camera Raw Filter ({layer}) Bộ lọc Camera Raw ({layer}) - Camera Raw isn't open Camera Raw chưa mở + RAW Develop Filter ({layer}) Bộ lọc Xử lý RAW ({layer}) + RAW Develop isn't open Xử lý RAW chưa mở Cancel Hủy Clarity Độ rõ Color Màu @@ -1551,7 +1551,7 @@ cameraRaw Shadows Vùng tối Both Cả hai Brush picker Bộ chọn cọ Cache tile size Kích thước ô đệm - Camera Raw Defaults Mặc định Camera Raw + RAW Defaults Mặc định RAW Canvas border Viền canvas Canvas color Màu canvas Canvas custom color Màu canvas tùy chỉnh @@ -1747,7 +1747,6 @@ cameraRaw Shadows Vùng tối Default restored. Đã khôi phục mặc định. Delete Shortcut Xóa phím tắt Reset All to Defaults Đặt lại tất cả về mặc định - All shortcuts reset to Photoshop defaults. Tất cả phím tắt đã được đặt lại về mặc định Photoshop. Show All Menu Items Hiện tất cả mục menu Restore Defaults Khôi phục mặc định Visible Hiện @@ -1809,7 +1808,7 @@ cameraRaw Shadows Vùng tối Export Presets Xuất thiết lập sẵn Import Presets Nhập thiết lập sẵn Fit in View Vừa khung nhìn - Camera Raw Camera Raw + RAW Develop Xử lý RAW cameraRaw Color Màu cameraRaw Effects Hiệu ứng cameraRaw Whites Điểm trắng @@ -1872,7 +1871,6 @@ cameraRaw Size Kích thước White Trắng Transparent Trong suốt Portrait Dọc - Default Photoshop Size Kích thước Photoshop mặc định document Orientation Hướng trang Image Size Kích thước ảnh Image Size: Kích thước ảnh: @@ -2094,7 +2092,7 @@ layers Fill: Độ tô: Scope Phạm vi Selected Đã chọn Open Mở - Camera Raw ({name}) Camera Raw ({name}) + RAW Develop ({name}) Xử lý RAW ({name}) Developing {name} Đang xử lý {name} 101 by 101 Average Trung bình 101 × 101 11 by 11 Average Trung bình 11 × 11 @@ -2637,7 +2635,7 @@ shape Appearance Diện mạo Delete and Fill Selection Xoá và tô vùng chọn Transform Again on a Copy Biến đổi lại trên một bản sao General… Chung… - Camera Raw… Camera Raw… + RAW Defaults… Mặc định RAW… Integrations… Tích hợp… Stamp Visible Đóng dấu lớp hiện thấy Select Layer Above Chọn lớp phía trên @@ -2811,7 +2809,6 @@ shape Appearance Diện mạo Missing glyph protection Bảo vệ khi thiếu glyph Modern Hiện đại Open as smart object Mở dưới dạng đối tượng thông minh - Open in camera raw Mở trong camera raw Open documents as tabs Mở tài liệu dưới dạng thẻ Print resolution Độ phân giải in Pro light Pro sáng @@ -3043,7 +3040,7 @@ cameraData Lens Ống kính Burn Làm tối Calculations Tính toán Camera Calibration Hiệu chuẩn máy ảnh - Camera Raw Filter Bộ lọc Camera Raw + RAW Develop Filter Bộ lọc Xử lý RAW Candle Light Ánh nến Canvas Size Kích thước vùng vẽ Caption Chú thích @@ -4018,8 +4015,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp Dải thang xám Current Colors Màu hiện tại Make Ramp Web Safe Giới hạn dải màu ở màu web + Scroll All Windows Cuộn mọi cửa sổ The path was kept as the Work Path Đường dẫn được giữ lại làm Đường dẫn làm việc The path was discarded Đường dẫn đã bị loại bỏ +# Art History Brush (#213). Art History Brush Cọ lịch sử nghệ thuật Art History Brush Tool Công cụ Cọ lịch sử nghệ thuật Tight Short Chặt ngắn @@ -4111,6 +4110,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. Chọn một tài liệu khác cho mỗi kênh. A picked document is no longer open. Một tài liệu đã chọn không còn mở. A picked document is no longer a grayscale document of the same size. Một tài liệu đã chọn không còn là tài liệu thang xám cùng kích thước. + Netscape Gray Xám Netscape # Move tool options bar (#11381) Align top edges Căn các cạnh trên Align vertical centers Căn các tâm dọc @@ -4120,7 +4120,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover Hiện ranh giới lớp khi di chuột Expand layer group on click Mở rộng nhóm lớp khi nhấp Show hover bounds from Layers Hiện ranh giới khi di chuột từ bảng Lớp - Saved Camera Raw settings to {file} Đã lưu cài đặt Camera Raw vào {file} + Saved RAW Develop settings to {file} Đã lưu cài đặt Xử lý RAW vào {file} Save the settings to each raw's sidecar without opening it Lưu thiết lập vào tệp sidecar của từng ảnh raw mà không mở No settings saved: these raws can't keep a sidecar here Không lưu được gì: các ảnh raw này không thể có tệp sidecar ở đây Some settings could not be saved; the raws stay open Không thể lưu một số cài đặt; các ảnh raw vẫn mở @@ -4132,3 +4132,5 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas Tự động đổi kích thước vùng vẽ Keep Relative Position During Layer Reordering Giữ vị trí tương đối khi sắp xếp lại lớp Shrinkwrap Canvas on Save Thu nhỏ vùng vẽ theo nội dung khi lưu + Move Toolbar to the Right Di chuyển thanh công cụ sang phải + Move Toolbar to the Left Di chuyển thanh công cụ sang trái diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 28c6119f66..593a09ab2b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -26,7 +26,7 @@ # Layers-panel trash confirmation -# Camera Raw: contextual controls and window title +# RAW Develop: contextual controls and window title # Current shell labels and shortcut templates. Keep {key} platform-dependent. # Gradient Editor window, opened from the options bar's gradient swatch. # Layer navigation, copy transforms and cancellable opening (labels added on main since this catalog). @@ -303,7 +303,6 @@ Histories 历史记录 Video Cache 视频缓存 All 全部 - Adobe PDF Presets… Adobe PDF 预设… Presets 预设 Preset Manager… 预设管理器… Migrate Presets 迁移预设 @@ -334,7 +333,7 @@ 3D… 3D… Enhanced Controls… 增强控件… Technology Previews… 技术预览… - Camera Raw… Camera Raw… + RAW Defaults… RAW 默认设置… Raw Defaults… Raw 默认设置… Integrations… 集成… AI Integrations… AI 集成… @@ -423,8 +422,8 @@ Artboard… 画板… Artboard from Group… 从组创建画板… Artboard from Layers… 从图层创建画板… - Layer via Copy 通过复制创建图层 - Layer via Cut 通过剪切创建图层 + Layer Via Copy 通过复制创建图层 + Layer Via Cut 通过剪切创建图层 Layer From Background… 从背景创建图层… Layer from Background… 从背景创建图层… Background From Layer 从图层创建背景 @@ -669,7 +668,7 @@ Last Filter 上次滤镜 Filter Gallery… 滤镜库… Adaptive Wide Angle… 自适应广角… - Camera Raw Filter… Camera Raw 滤镜… + RAW Develop Filter… RAW 显影 滤镜… Liquify… 液化… Vanishing Point… 消失点… Blur 模糊 @@ -1041,8 +1040,8 @@ Load Settings… 载入设置… Save these settings as a Camera Raw .xmp file 将这些设置存储为 Camera Raw .xmp 文件 Load settings from a Camera Raw .xmp file 从 Camera Raw .xmp 文件载入设置 - Loaded Camera Raw settings from {file} 已从 {file} 载入 Camera Raw 设置 - Loaded Camera Raw settings from {file} ({n} not supported) 已从 {file} 载入 Camera Raw 设置({n} 项不支持) + Loaded RAW Develop settings from {file} 已从 {file} 载入 RAW 显影 设置 + Loaded RAW Develop settings from {file} ({n} not supported) 已从 {file} 载入 RAW 显影 设置({n} 项不支持) Begin recording 开始录制 Bend: 弯曲: Bicubic 双三次 @@ -1070,7 +1069,7 @@ Brush Reconstruct Options 画笔重建选项 Brush Tool Options 画笔工具选项 Cache Level: 缓存级别: - Camera Raw isn't open 尚未打开 Camera Raw + RAW Develop isn't open 尚未打开 RAW 显影 Cancel 取消 Cancel (Esc) 取消(Esc) Manage submitted jobs in the system print queue 在系统打印队列中管理已提交的作业 @@ -2066,7 +2065,7 @@ Brush preview color 画笔预览颜色 Cache levels 缓存级别 Cache tile size 缓存图块大小 - Camera Raw Defaults Camera Raw 默认设置 + RAW Defaults RAW 默认设置 Canvas border 画布边框 Show canvas dots 显示画布圆点 Clip thumbnails to layer bounds 将缩略图裁剪到图层边界 @@ -2153,7 +2152,6 @@ Never 从不 Normal tip 正常笔尖 Open as smart object 作为智能对象打开 - Open in camera raw 在 Camera Raw 中打开 Open documents as tabs 以标签页打开文档 Overscroll 过度滚动 Performance 性能 @@ -2290,8 +2288,8 @@ Tone Histogram 色调直方图 Show Selected Region 显示选定区域 cameraRaw Light 光线 - Camera Raw Filter ({layer}) Camera Raw 滤镜({layer}) - Camera Raw ({name}) Camera Raw({name}) + RAW Develop Filter ({layer}) RAW 显影 滤镜({layer}) + RAW Develop ({name}) RAW 显影({name}) cameraRaw Lights 亮调 cameraRaw Darks 暗调 cameraRaw Blacks 黑色色阶 @@ -3184,8 +3182,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Exported {path} 已导出 {path} Exported {n} files 已导出 {n} 个文件 Driver: {driver} 驱动程序:{driver} + Scroll All Windows 滚动所有窗口 The path was kept as the Work Path 路径已保留为工作路径 The path was discarded 路径已丢弃 +# Art History Brush (#213). Art History Brush 艺术历史画笔 Art History Brush Tool 艺术历史画笔工具 Tight Short 紧密短 @@ -3298,6 +3298,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. 请为每个通道选择不同的文档。 A picked document is no longer open. 所选的一个文档已不再打开。 A picked document is no longer a grayscale document of the same size. 所选的一个文档已不再是同样大小的灰度文档。 + Netscape Gray Netscape 灰色 # Move tool options bar (#11381) Align top edges 顶端对齐 Align vertical centers 垂直居中对齐 @@ -3307,7 +3308,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover 悬停时显示图层边界 Expand layer group on click 单击时展开图层组 Show hover bounds from Layers 显示来自图层面板的悬停边界 - Saved Camera Raw settings to {file} 已将 Camera Raw 设置保存到 {file} + Saved RAW Develop settings to {file} 已将 RAW 显影 设置保存到 {file} Save the settings to each raw's sidecar without opening it 将设置保存到每个 Raw 的附属文件,不打开它 No settings saved: these raws can't keep a sidecar here 未保存任何内容:这些 Raw 在此处无法拥有附属文件 Some settings could not be saved; the raws stay open 部分设置无法保存;Raw 保持打开 @@ -3319,3 +3320,9 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas 自动调整画布大小 Keep Relative Position During Layer Reordering 重新排列图层时保持相对位置 Shrinkwrap Canvas on Save 保存时将画布缩至内容大小 + Move Toolbar to the Right 将工具栏移到右侧 + Move Toolbar to the Left 将工具栏移到左侧 + +# RAW Develop feature labels + RAW Develop RAW 显影 + RAW Develop Filter RAW 显影滤镜 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8d2c5697f1..85d6d589df 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -34,7 +34,7 @@ # Gradient Editor window, opened from the options bar's gradient swatch. # Rendering mode and recovery -# Camera Raw: contextual controls and window title +# RAW Develop: contextual controls and window title @@ -333,7 +333,7 @@ Plugins… 增效模組… Type… 文字… Enhanced Controls… 增強控制項… - Camera Raw… Camera Raw… + RAW Defaults… RAW 預設值… Raw Defaults… Raw 預設值… Integrations… 整合… AI Integrations… AI 整合… @@ -422,8 +422,8 @@ Artboard… 工作區域… Artboard from Group… 從群組建立工作區域… Artboard from Layers… 從圖層建立工作區域… - Layer via Copy 拷貝的圖層 - Layer via Cut 剪下的圖層 + Layer Via Copy 拷貝的圖層 + Layer Via Cut 剪下的圖層 Layer From Background… 從背景建立圖層… Layer from Background… 從背景建立圖層… Background from Layer 從圖層建立背景 @@ -668,7 +668,7 @@ Last Filter 上次濾鏡 Filter Gallery… 濾鏡收藏館… Adaptive Wide Angle… 最適化廣角… - Camera Raw Filter… Camera Raw 濾鏡… + RAW Develop Filter… RAW 顯影 濾鏡… Liquify… 液化… Vanishing Point… 消失點… Blur 模糊 @@ -1024,8 +1024,8 @@ Load Settings… 載入設定… Save these settings as a Camera Raw .xmp file 將這些設定儲存為 Camera Raw .xmp 檔案 Load settings from a Camera Raw .xmp file 從 Camera Raw .xmp 檔案載入設定 - Loaded Camera Raw settings from {file} 已從 {file} 載入 Camera Raw 設定 - Loaded Camera Raw settings from {file} ({n} not supported) 已從 {file} 載入 Camera Raw 設定({n} 項不支援) + Loaded RAW Develop settings from {file} 已從 {file} 載入 RAW 顯影 設定 + Loaded RAW Develop settings from {file} ({n} not supported) 已從 {file} 載入 RAW 顯影 設定({n} 項不支援) Begin recording 開始記錄 Bend: 彎曲: Bicubic 雙三次 @@ -1053,7 +1053,7 @@ Brush Reconstruct Options 筆刷重建選項 Brush Tool Options 筆刷工具選項 Cache Level: 快取層級: - Camera Raw isn't open Camera Raw 未開啟 + RAW Develop isn't open RAW 顯影 未開啟 Cancel 取消 Cancel (Esc) 取消 (Esc) Manage submitted jobs in the system print queue 在系統列印佇列中管理已提交的工作 @@ -2035,7 +2035,7 @@ Brush preview color 筆刷預視顏色 Cache levels 快取層級 Cache tile size 快取拼貼大小 - Camera Raw Defaults Camera Raw 預設值 + RAW Defaults RAW 預設值 Canvas border 畫布邊框 Show canvas dots 顯示畫布圓點 Clip thumbnails to layer bounds 將縮圖裁切至圖層邊界 @@ -2122,7 +2122,6 @@ Never 永不 Normal tip 一般筆尖 Open as smart object 以智慧型物件開啟 - Open in camera raw 在 Camera Raw 中開啟 Open documents as tabs 以索引標籤開啟文件 Overscroll 超出捲動 Performance 效能 @@ -2401,8 +2400,8 @@ Tone Histogram 色調直方圖 Show Selected Region 顯示選取區域 cameraRaw Light 光線 - Camera Raw Filter ({layer}) Camera Raw 濾鏡({layer}) - Camera Raw ({name}) Camera Raw({name}) + RAW Develop Filter ({layer}) RAW 顯影 濾鏡({layer}) + RAW Develop ({name}) RAW 顯影({name}) cameraRaw Lights 亮調 cameraRaw Darks 暗調 cameraRaw Blacks 黑色色階 @@ -3141,8 +3140,10 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Grayscale Ramp 灰階色帶 Current Colors 目前色彩 Make Ramp Web Safe 讓色帶成為網頁安全色 + Scroll All Windows 捲動所有視窗 The path was kept as the Work Path 路徑已保留為工作路徑 The path was discarded 路徑已捨棄 +# Art History Brush (#213). Art History Brush 藝術歷史畫筆 Art History Brush Tool 藝術歷史畫筆工具 Tight Short 緊密短 @@ -3255,6 +3256,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Pick a different document for each channel. 請為每個色版選擇不同的文件。 A picked document is no longer open. 所選的一個文件已不再開啟。 A picked document is no longer a grayscale document of the same size. 所選的一個文件已不再是相同大小的灰階文件。 + Netscape Gray Netscape 灰色 # Move tool options bar (#11381) Align top edges 對齊頂端 Align vertical centers 垂直置中對齊 @@ -3264,7 +3266,7 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Show layer bounds on hover 滑過時顯示圖層邊界 Expand layer group on click 按一下時展開圖層群組 Show hover bounds from Layers 顯示來自圖層面板的滑過邊界 - Saved Camera Raw settings to {file} 已將 Camera Raw 設定儲存到 {file} + Saved RAW Develop settings to {file} 已將 RAW 顯影 設定儲存到 {file} Save the settings to each raw's sidecar without opening it 將設定儲存到每個 Raw 的附屬檔案,不開啟它 No settings saved: these raws can't keep a sidecar here 未儲存任何內容:這些 Raw 在此處無法擁有附屬檔案 Some settings could not be saved; the raws stay open 部分設定無法儲存;Raw 保持開啟 @@ -3276,3 +3278,9 @@ smartSvg AI/PDF/EPS contents will be edited as SVG. Saving replaces the embedded Auto-size Canvas 自動調整版面尺寸 Keep Relative Position During Layer Reordering 重新排列圖層時保持相對位置 Shrinkwrap Canvas on Save 儲存時將版面縮至內容大小 + Move Toolbar to the Right 將工具列移到右側 + Move Toolbar to the Left 將工具列移到左側 + +# RAW Develop feature labels + RAW Develop RAW 顯影 + RAW Develop Filter RAW 顯影濾鏡 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 93103b34a3..5934e11352 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -110,6 +110,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("paint-bucket", include_bytes!("../../../assets/icons/paint-bucket.svg")), ("painting-symmetry", include_bytes!("../../../assets/icons/painting-symmetry.svg")), ("palette", include_bytes!("../../../assets/icons/palette.svg")), + ("panel-left", include_bytes!("../../../assets/icons/panel-left.svg")), ("panel-right", include_bytes!("../../../assets/icons/panel-right.svg")), ("panels-top-left", include_bytes!("../../../assets/icons/panels-top-left.svg")), ("path-op-combine", include_bytes!("../../../assets/icons/path-op-combine.svg")), @@ -182,6 +183,9 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("type-mask-vertical", include_bytes!("../../../assets/icons/type-mask-vertical.svg")), ("undo-2", include_bytes!("../../../assets/icons/undo-2.svg")), ("unlink", include_bytes!("../../../assets/icons/unlink.svg")), + ("vertical-align-bottom", include_bytes!("../../../assets/icons/vertical-align-bottom.svg")), + ("vertical-align-middle", include_bytes!("../../../assets/icons/vertical-align-middle.svg")), + ("vertical-align-top", include_bytes!("../../../assets/icons/vertical-align-top.svg")), ("wand", include_bytes!("../../../assets/icons/wand.svg")), ("wand-sparkles", include_bytes!("../../../assets/icons/wand-sparkles.svg")), ("x", include_bytes!("../../../assets/icons/x.svg")), diff --git a/crates/ui-egui/src/input/blend_keys.rs b/crates/ui-egui/src/input/blend_keys.rs index fb3d5d47b5..ebb018b381 100644 --- a/crates/ui-egui/src/input/blend_keys.rs +++ b/crates/ui-egui/src/input/blend_keys.rs @@ -202,10 +202,19 @@ fn set_tool_mode(app: &mut PhotocraftApp, mode: Option) { _ => {} } crate::paint_mouse::sync_tool_brush(app); + // Behind is one of the painting modes in the reference application: picking any other mode + // (Clear too) leaves it, in the same one command (#11896). With Behind off, as before. + let mut brush = serde_json::Map::new(); if let Some(m) = mode && let Ok(m) = serde_json::to_value(m) { - let _ = app.run("tools.setBrush", json!({ "brush": { "mode": m } })); + brush.insert("mode".into(), m); + } + if app.session.tools.brush.behind { + brush.insert("behind".into(), json!(false)); + } + if !brush.is_empty() { + let _ = app.run("tools.setBrush", json!({ "brush": brush })); } } @@ -299,3 +308,7 @@ mod tests; #[cfg(test)] #[path = "../brush_behind_key_tests.rs"] mod brush_behind_key_tests; + +#[cfg(test)] +#[path = "../brush_blend_keys_behind_tests.rs"] +mod brush_blend_keys_behind_tests; diff --git a/crates/ui-egui/src/input/opacity_keys.rs b/crates/ui-egui/src/input/opacity_keys.rs index 55044a26f1..6ccda86995 100644 --- a/crates/ui-egui/src/input/opacity_keys.rs +++ b/crates/ui-egui/src/input/opacity_keys.rs @@ -1,6 +1,7 @@ //! Number keys set opacity (#352): 1 = 10% … 9 = 90%, 0 = 100%; two digits //! typed quickly set an exact value (4 then 5 = 45%; 0 then 0 = 100% for the Brush and the Pencil, #11812). With the Brush, Pencil or -//! Eraser they set the brush's Opacity (⇧: Flow; swapped while airbrush build-up is on); with the Gradient or Paint Bucket their +//! Eraser they set the brush's Opacity (⇧: Flow, swapped while airbrush build-up is on; the Pencil has no Flow, so its ⇧ +//! digits set Opacity too, #11967); with the Gradient or Paint Bucket their //! Opacity; with tools that have no opacity of their own (Move, the selection tools, Type…) the //! active layer's Opacity (⇧: Fill); with the Background Eraser its Tolerance (#11907). Tools whose //! number is a strength or exposure are left alone. @@ -110,7 +111,8 @@ fn apply(app: &mut PhotocraftApp, percent: f32, shift: bool) { let build_up = app.session.tools.brush.build_up && !crate::eraser_ui::pencil_mode(app, tool) && !crate::eraser_ui::block_mode(app, tool); let shift = shift ^ (build_up && matches!(target(tool), Target::Brush { flow: true })); match (target(app.ui.tool), shift) { - (Target::Brush { .. }, false) => { + // The Pencil has no Flow: its ⇧ digits set Opacity like the plain ones (#11967). + (Target::Brush { flow: false }, _) | (Target::Brush { flow: true }, false) => { // The painting tools' Opacity fields (and `tools.setBrush`) start at 1%, so `00` sets the // 1% they actually paint with rather than a 0% they can't do. The Brush's and the // Pencil's `00` is 100%, as in Photoshop (#11812); only `00` gives 0 here. diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index c3ef377874..d525dc2a0b 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -907,8 +907,9 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::opacity_keys::handle(app, ctx); } -/// Selects a tool from its letter key. Pressing the key of the current group cycles within it; with -/// the Shift-switch preference only ⇧+key cycles. Returns true when a tool key was handled. +/// Selects a tool from its letter key. Entering a group uses its remembered eligible tool or the +/// first eligible tool in toolbar order. Pressing the key of the current group cycles within it. +/// With the Shift-switch preference, only ⇧+key cycles. Returns true when a tool key was handled. fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &impl Fn(Key) -> bool) -> bool { let shift_switch = app.session.prefs().tools.use_shift_key_for_tool_switch; for t in Tool::ALL { @@ -920,15 +921,20 @@ fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &im if cycle_shift || pressed(k) { let before = app.ui.tool; let mut group: Vec = Tool::ALL.iter().copied().filter(|x| x.key() == t.key() && crate::tool_shortcuts::uses_default(app, *x)).collect(); - // Shift+key (the cycle and the fallback to the group's first tool) uses the toolbar - // flyout's order; plain keys keep the `Tool::ALL` order. + // Shift+key cycles in toolbar flyout order. if cycle_shift { group.sort_by_key(|x| crate::panels::toolbar::toolbar_position(*x)); } app.ui.tool = match group.iter().position(|x| *x == app.ui.tool) { Some(i) if shift_switch && !cycle_shift => group[i], Some(i) => group[(i + 1) % group.len()], - None => app.ui.group_tools.iter().copied().find(|last| group.contains(last)).unwrap_or(group[0]), + None => app + .ui + .group_tools + .iter() + .copied() + .find(|last| group.contains(last)) + .unwrap_or_else(|| group.iter().copied().min_by_key(|tool| crate::panels::toolbar::toolbar_position(*tool)).unwrap_or(t)), }; crate::tool_memory::ended_by_tool(app); // `consume_key` ignores extra ⇧ and ⌥: a ⇧/⌥ switch is never spring-loaded. @@ -946,3 +952,7 @@ fn select_tool_by_key(app: &mut PhotocraftApp, ctx: &egui::Context, pressed: &im #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "tool_key_default_tests.rs"] +mod tool_key_default_tests; diff --git a/crates/ui-egui/src/input/tool_key_default_tests.rs b/crates/ui-egui/src/input/tool_key_default_tests.rs new file mode 100644 index 0000000000..5b846d5e7f --- /dev/null +++ b/crates/ui-egui/src/input/tool_key_default_tests.rs @@ -0,0 +1,89 @@ +use super::{Key, Modifiers, PhotocraftApp, Tool, handle}; +use crate::panels::toolbar::TOOL_SECTIONS; +use crate::spring_tools::key_of; +use std::collections::HashSet; + +fn app() -> PhotocraftApp { + PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()) +} + +fn press(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, modifiers: Modifiers) { + let raw = egui::RawInput { + events: vec![ + egui::Event::ModifiersChanged(modifiers), + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }, + ], + ..Default::default() + }; + ctx.begin_pass(raw); + handle(app, ctx); + ctx.end_pass().textures_delta.clear(); +} + +/// A fresh app enters each default letter group at its first toolbar tool under either preference. +#[test] +fn fresh_tool_letters_pick_the_first_tool_in_toolbar_order() { + for shift_switch in [true, false] { + let mut checked = HashSet::new(); + for tool in TOOL_SECTIONS.iter().flat_map(|section| section.iter()).flat_map(|slot| slot.iter()).copied() { + let Some(key) = key_of(tool.key()) else { continue }; + if !checked.insert(key) { + continue; + } + + let mut app = app(); + app.session.edit_prefs(|prefs| prefs.tools.use_shift_key_for_tool_switch = shift_switch); + if app.ui.tool.key() == tool.key() { + app.ui.tool = Tool::Brush; + } + press(&mut app, &egui::Context::default(), key, Modifiers::NONE); + assert_eq!(app.ui.tool, tool, "{key:?}, Shift switch: {shift_switch}"); + } + assert_eq!(checked, Tool::ALL.into_iter().filter_map(|tool| key_of(tool.key())).collect::>()); + } +} + +/// A remembered Magic Wand takes precedence over the fresh W default, even when hidden. +#[test] +fn plain_w_returns_to_the_remembered_magic_wand() { + for hidden in [false, true] { + let mut app = app(); + let ctx = egui::Context::default(); + if hidden { + app.session.edit_prefs(|prefs| prefs.toolbar.hidden = vec!["MagicWand".to_owned()]); + } + app.ui.tool = Tool::MagicWand; + press(&mut app, &ctx, Key::B, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::Brush); + press(&mut app, &ctx, Key::W, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::MagicWand, "hidden: {hidden}"); + } +} + +/// Shift+W follows the flyout order and wraps. With the default preference, plain W keeps +/// the current tool when it already belongs to the group. +#[test] +fn shift_w_cycles_in_toolbar_order() { + let mut app = app(); + let ctx = egui::Context::default(); + app.ui.tool = Tool::ObjectSelection; + + for expected in [Tool::QuickSelection, Tool::MagicWand, Tool::ObjectSelection] { + press(&mut app, &ctx, Key::W, Modifiers::SHIFT); + assert_eq!(app.ui.tool, expected); + } + press(&mut app, &ctx, Key::W, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::ObjectSelection); +} + +#[test] +fn remapped_first_tool_is_skipped_by_its_default_letter() { + let mut app = app(); + let ctx = egui::Context::default(); + app.run("prefs.set", serde_json::json!({"path": "shortcuts.tools.select.objectSelection", "value": "F6"})).unwrap(); + press(&mut app, &ctx, Key::W, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::QuickSelection); + press(&mut app, &ctx, Key::F6, Modifiers::NONE); + assert_eq!(app.ui.tool, Tool::ObjectSelection); +} diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index c4ff5397c2..7459f54be6 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -286,11 +286,38 @@ pub fn start_open( // once. A preflight keeps the slot and set order in its memory prompt. Started::Done(v) => finish_open(app, name, path.as_deref(), &v, slot, order), Started::Job(job) => { - app.jobs.opens.push(OpenTab { job, name: name.to_string(), path, slot, order }); - app.jobs.focus = Some(job); - app.ui.chrome.home = None; - app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", name)]); - app.ui.status_error = false; + track_open(app, OpenTab { job, name: name.to_string(), path, slot, order }); + Ok(()) + } + } +} + +/// A file opening in the background gets its tab: focused, with the status line naming it. +fn track_open(app: &mut PhotocraftApp, tab: OpenTab) { + app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", &tab.name)]); + app.jobs.focus = Some(tab.job); + app.jobs.opens.push(tab); + app.ui.chrome.home = None; + app.ui.status_error = false; +} + +/// File › Open as Smart Object… for one file: `file.openAsSmartObject` as a tracked open job, so +/// the result goes through File › Open's completion ([`finish_open`]: the profile prompt, the +/// Camera Raw open dialog for a raw, the import warnings). The document is untitled, so +/// Open Recent is untouched. Inline (background jobs off, or the web) it finishes at once. +pub(crate) fn start_open_as_smart_object(app: &mut PhotocraftApp, path: &str, order: Option) -> Result<(), String> { + let name = crate::file_open::display_name(path); + // `confirmDamage`: a damaged PSD waits for the user's answer, as in File › Open. + let params = json!({"path": path, "confirmDamage": true}); + let started = if app.background_jobs { + app.session.start("file.openAsSmartObject", params).map_err(|e| e.to_string())? + } else { + Started::Done(app.session.execute("file.openAsSmartObject", params).map_err(|e| e.to_string())?) + }; + match started { + Started::Done(v) => finish_open(app, &name, None, &v, None, order), + Started::Job(job) => { + track_open(app, OpenTab { job, name, path: None, slot: None, order }); Ok(()) } } @@ -608,7 +635,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { finish_save(app, ctx, save, &e.label, e.outcome); return; } - if e.command == OPEN_JOB { + if e.command == OPEN_JOB || app.jobs.opens.iter().any(|o| o.job == e.id) { let Some(i) = app.jobs.opens.iter().position(|o| o.job == e.id) else { return }; let tab = app.jobs.opens.remove(i); match e.outcome { @@ -703,6 +730,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu order, question, policy_applied, + smart_object: v.get("smartObject").and_then(Value::as_bool).unwrap_or(false), }; // Held back for the profile prompt (Ask When Opening). if let Some(id) = v.get("held").and_then(Value::as_u64) { diff --git a/crates/ui-egui/src/layer_via_label_tests.rs b/crates/ui-egui/src/layer_via_label_tests.rs new file mode 100644 index 0000000000..b8a20c3b27 --- /dev/null +++ b/crates/ui-egui/src/layer_via_label_tests.rs @@ -0,0 +1,63 @@ +//! "Layer Via Copy" and "Layer Via Cut" carry a capital V in every menu, as in the reference +//! application (#12357), and every translation moved with the key. + +use crate::canvas::canvas_tool_menu::SELECTION_MENU; +use crate::menu_catalog::CATALOG; + +const NEW: [(&str, &str); 2] = [("Layer Via Copy", "layer.new.layerViaCopy"), ("Layer Via Cut", "layer.new.layerViaCut")]; +const OLD: [&str; 2] = ["Layer via Copy", "Layer via Cut"]; + +#[test] +fn menu_bar_rows_use_the_capital_v() { + for (label, id) in NEW { + let row = CATALOG.iter().find(|r| r.3 == id).expect("catalog row"); + assert_eq!(row.1, label); + } + assert!(CATALOG.iter().all(|r| !OLD.contains(&r.1))); +} + +#[test] +fn command_labels_use_the_capital_v() { + let specs = photocraft_engine::cmd::command_specs(); + for (label, id) in NEW { + let spec = specs.iter().find(|s| s.id == id).expect("command spec"); + assert_eq!(spec.label, label); + } +} + +#[test] +fn selection_tools_canvas_menu_uses_the_capital_v() { + for (label, id) in NEW { + assert!(SELECTION_MENU.iter().flatten().any(|r| *r == (label, id)), "{label} row"); + } + assert!(SELECTION_MENU.iter().flatten().all(|r| !OLD.contains(&r.0))); +} + +#[test] +fn every_locale_file_keeps_its_translation_under_the_new_keys() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/i18n"); + let mut checked = 0; + for entry in std::fs::read_dir(dir).expect("i18n dir") { + let path = entry.expect("entry").path(); + if path.extension().and_then(|e| e.to_str()) != Some("tsv") { + continue; + } + let text = std::fs::read_to_string(&path).expect("tsv"); + let keys: Vec<&str> = text.lines().filter_map(|l| l.split('\t').nth(1)).collect(); + let name = path.display(); + assert!(OLD.iter().all(|o| !keys.contains(o)), "{name} still has an old key"); + // Hindi has no entries for these menus yet; every other file has both. + if keys.contains(&"Layer Via Copy") || keys.contains(&"Layer Via Cut") { + assert!(NEW.iter().all(|(n, _)| keys.contains(n)), "{name} lacks a new key"); + checked += 1; + } + } + assert!(checked >= 30, "only {checked} locale files carry the keys"); +} + +#[test] +fn a_translation_is_found_under_the_new_key() { + let de = crate::i18n::Lang::from_code("de").expect("German"); + assert_eq!(crate::i18n::tr(de, "Layer Via Copy"), "Ebene durch Kopieren"); + assert_eq!(crate::i18n::tr(de, "Layer Via Cut"), "Ebene durch Ausschneiden"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47d6d7740f..55af69bb3b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -112,6 +112,7 @@ pub use canvas::pixel_grid; pub use canvas::quick_pick; pub use canvas::rotate_view; pub use canvas::rulers; +pub use canvas::scroll_all_windows; pub use canvas::scrollbars; pub use canvas::select_mask_view; pub use canvas::snap_ui; @@ -262,8 +263,8 @@ pub use services::{ AdoptAutosaveFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, CaptionStyleFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, - LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, Recoverable, RightButtonDownFn, - SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, + LastUpdateFn, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, Recoverable, + RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, }; pub use text::bidi_text; pub use text::cjk_fonts; @@ -276,8 +277,10 @@ use tools::align_bar; pub use tools::analysis_ui; pub use tools::anchor_tools; pub use tools::artboard_tool; +pub use tools::bg_eraser_popup; pub(crate) use tools::brush_cursor; pub use tools::brush_picker; +pub use tools::brush_refusal; pub use tools::brush_resize; use tools::cam_transform; pub use tools::cas_transform; @@ -485,6 +488,9 @@ pub struct PhotocraftApp { /// Window › Arrange: the first document of the shown run of tiles, when there are more /// documents than tiles (`canvas::arranged_cells`). pub(crate) arrange_start: usize, + /// The document window (`DocWindow::id`) whose canvas `canvas::extra_windows` is drawing. + /// `scroll_all_windows::source` reads it to skip the view that a Hand drag moves itself. + pub(crate) drawing_window: Option, /// Physical pixels per egui point of the canvas last frame (`ctx.pixels_per_point`, which /// folds in both the display scale and Interface › UI Scale). The canvas maps document pixels /// to physical pixels, so point-space geometry divides the view zoom by this (see @@ -584,6 +590,10 @@ pub struct PhotocraftApp { pub(crate) hist_uncached: Option<(DocId, u64)>, /// Free Transform preview (document without the moving pixels + their texture). pub(crate) transform_preview: Option, + /// The canvas area the last Free Transform box's preview changes (`transform_tool::damage`). + transform_area: Option, + /// A large layer's Free Transform box being prepared in the background. + transform_preparing: Option, /// Move-tool ⇧/⌥ drag state (move_mods). pub(crate) move_mods: move_mods::MoveDrag, /// Cached document for a modal text Style Options color preview. @@ -781,6 +791,14 @@ mod brush_options_tooltips_tests; #[cfg(test)] mod brush_picker_escape_tests; #[cfg(test)] +mod cam_no_pixels_alert_tests; +#[cfg(test)] +mod eyedropper_context_menu_tests; +#[cfg(test)] +mod patch_shift_constrain_tests; +#[cfg(test)] +mod pencil_pressure_toggles_tests; +#[cfg(test)] mod shape_bounds_box_tests; #[cfg(test)] @@ -903,12 +921,18 @@ mod color_tab_theme_tests; #[cfg(test)] mod new_layer_button_tests; +#[cfg(test)] +mod layer_via_label_tests; + #[cfg(test)] mod smart_filter_rows_tests; #[cfg(test)] mod blur_pins_tests; +#[cfg(test)] +mod filter_preview_locator_tests; + #[cfg(test)] mod move_outline_tests; @@ -984,6 +1008,8 @@ mod status_bar_tests; #[cfg(test)] mod stroke_timing_tests; +#[cfg(test)] +mod patch_tool_history_names_tests; #[cfg(test)] mod polygon_lasso_step_snap_tests; #[cfg(test)] @@ -1012,12 +1038,20 @@ mod pen_path_ownership_tests; #[cfg(test)] mod artboard_options_bar_tests; #[cfg(test)] +mod background_eraser_bar_angle_tests; +#[cfg(test)] mod brush_opacity_minimum_tests; + +#[cfg(test)] +mod pencil_shift_digit_opacity_tests; + #[cfg(test)] mod doc_tab_menu_tests; #[cfg(test)] mod layers_empty_area_menu_tests; #[cfg(test)] +mod pencil_auto_erase_tooltip_tests; +#[cfg(test)] mod preferences_submenu_tests; #[cfg(test)] mod selection_move_step_tests; diff --git a/crates/ui-egui/src/live_retouch_tests.rs b/crates/ui-egui/src/live_retouch_tests.rs index dff475cde4..ed9f7601f4 100644 --- a/crates/ui-egui/src/live_retouch_tests.rs +++ b/crates/ui-egui/src/live_retouch_tests.rs @@ -119,14 +119,15 @@ fn background_eraser_draws_live_and_commits_what_it_showed() { fn a_refused_background_eraser_stroke_shows_nothing_and_reports_on_release() { let mut app = app(8, Tool::BackgroundEraser); app.run("layer.new.layer", json!({})).unwrap(); - app.run("layer.setProps", json!({"locks": {"transparency": true}})).unwrap(); + // Lock image pixels refuses (Lock transparent pixels does not, #11905). + app.run("layer.setProps", json!({"locks": {"pixels": true}})).unwrap(); let steps = app.session.active().unwrap().history.past_len(); let m = Modifiers::NONE; tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); tool_event(&mut app, ToolEvent::Move { x: 40.0, y: 20.0, pressure: 1.0 }, m); assert!(app.live_stroke.is_none(), "the engine refuses the stroke, so nothing is drawn live"); tool_event(&mut app, ToolEvent::Up { x: 40.0, y: 20.0 }, m); - assert!(app.ui.status_error && app.ui.status.contains("transparency"), "{}", app.ui.status); + assert!(app.ui.status_error && app.ui.status.contains("is locked"), "{}", app.ui.status); assert_eq!(app.session.active().unwrap().history.past_len(), steps); } diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index 3838a70bcf..d6db835eab 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -7,6 +7,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["File"], "New…", Some("Cmd+N"), "file.new"), (&["File"], "Open…", Some("Cmd+O"), "file.open"), (&["File"], "Open As…", Some("Cmd+Alt+Shift+O"), "file.openAs"), + (&["File"], "Open as Smart Object…", None, "file.openAsSmartObject"), (&["File"], "Open EXR Parts…", None, "file.openExrParts"), (&["File"], "---", None, "---"), (&["File"], "Close", Some("Cmd+W"), "file.close"), @@ -167,7 +168,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Edit", "Preferences"], "Type…", None, "edit.preferences.type"), (&["Edit", "Preferences"], "Enhanced Controls…", None, "edit.preferences.enhancedControls"), (&["Edit", "Preferences"], "---", None, "---"), - (&["Edit", "Preferences"], "Camera Raw…", None, "edit.preferences.rawDefaults"), + (&["Edit", "Preferences"], "RAW Defaults…", None, "edit.preferences.rawDefaults"), (&["Image", "Mode"], "Bitmap", None, "image.mode.bitmap"), (&["Image", "Mode"], "Grayscale", None, "image.mode.grayscale"), (&["Image", "Mode"], "Duotone", None, "image.mode.duotone"), @@ -256,8 +257,9 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Layer", "New"], "Artboard from Layers…", None, "layer.new.artboardFromLayers"), (&["Layer", "New"], "Frame from Layers", None, "layer.new.frameFromLayers"), (&["Layer", "New"], "---", None, "---"), - (&["Layer", "New"], "Layer via Copy", Some("Cmd+J"), "layer.new.layerViaCopy"), - (&["Layer", "New"], "Layer via Cut", Some("Cmd+Shift+J"), "layer.new.layerViaCut"), + (&["Layer", "New"], "Layer Via Copy", Some("Cmd+J"), "layer.new.layerViaCopy"), + (&["Layer", "New"], "Layer Via Cut", Some("Cmd+Shift+J"), "layer.new.layerViaCut"), + (&["Layer"], "Copy CSS", None, "layer.copyCSS"), (&["Layer"], "Duplicate Layer…", None, "layer.duplicate"), (&["Layer", "Delete"], "Layer", None, "layer.delete"), (&["Layer", "Delete"], "Hidden Layers", None, "layer.delete.hiddenLayers"), @@ -569,7 +571,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Filter"], "Convert for Smart Filters", None, "filter.convertForSmartFilters"), (&["Filter"], "---", None, "---"), (&["Filter"], "Filter Gallery…", None, "filter.filterGallery"), - (&["Filter"], "Camera Raw Filter…", Some("Cmd+Shift+A"), "filter.cameraRaw"), + (&["Filter"], "RAW Develop Filter…", Some("Cmd+Shift+A"), "filter.cameraRaw"), (&["Filter"], "Adaptive Wide Angle…", Some("Cmd+Alt+Shift+A"), "filter.adaptiveWideAngle"), (&["Filter"], "Lens Correction…", Some("Cmd+Shift+R"), "filter.lensCorrection"), (&["Filter"], "Liquify…", Some("Cmd+Shift+X"), "filter.liquify"), diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 9e2da7e511..cbe858eba6 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -86,6 +86,14 @@ fn invoke_early_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, if id == "help.checkForUpdates" { return Some(crate::updates_ui::check(app, ctx, params.clone())); } + // Layer › Copy CSS: the engine writes the CSS, the clipboard is the shell's (#9372). + if id == photocraft_engine::layer_css_cmds::ID { + return Some(app.run(id, params.clone()).inspect(|r| { + if let Some(css) = r.get("css").and_then(Value::as_str) { + ctx.copy_text(css.to_string()); + } + })); + } if id == "ui.symmetryTransform" { return Some(crate::symmetry_ui::begin(app).map(|_| Value::Null)); } diff --git a/crates/ui-egui/src/menus/native_menu.rs b/crates/ui-egui/src/menus/native_menu.rs index 88106d1304..2457586722 100644 --- a/crates/ui-egui/src/menus/native_menu.rs +++ b/crates/ui-egui/src/menus/native_menu.rs @@ -10,7 +10,9 @@ //! - **Window** gets Minimize, Zoom and Bring All to Front, with the open documents after it //! (where a Mac app lists its windows), and **Help** the system search field; //! - **clashes** with the system's keys (⌘H, ⌘M, ⌘W, ⌘,) are resolved in PhotoCraft's favour, and -//! reported; Hide and Minimize move to ⌃⌘H and ⌃⌘M, as Photoshop does. +//! reported; Hide and Minimize move to ⌃⌘H and ⌃⌘M, as Photoshop does. [`app_layout`] reads +//! who owns a key from dispatch, so a saved key on a command with no menu item, or an +//! alternate key, takes it from the system item too. //! //! **Keys stay with egui.** AppKit runs a menu's key equivalents before the window sees the key, //! which would skip PhotoCraft's key rules (text fields keep ⌘C/⌘V/⌘Z, dialogs and Camera Raw are @@ -388,6 +390,14 @@ pub fn mac_layout(bar: &MenuBar, lang: Lang) -> Layout { let mut clashes = Vec::new(); let bound: HashMap = bar.items().iter().filter_map(|it| Some((Chord::parse(it.shortcut.as_deref()?)?.portable(), it.id.clone()))).collect(); let taken = |sc: &str, own: Option<&str>| bound.get(sc).filter(|cmd| Some(cmd.as_str()) != own).cloned(); + // Every ⌘, owner, read before About, Quit and Appearance leave the bar: `bound` keeps only one + // per key, and a saved key (Hide Layers on ⌘,, as in Photoshop) can share it with Settings. + let comma_owners: Vec = bar + .items() + .into_iter() + .filter(|it| it.shortcut.as_deref().and_then(Chord::parse).is_some_and(|c| c.portable() == "Cmd+,")) + .map(|it| it.id.clone()) + .collect(); let named = |s: &str| crate::i18n::fmt(tr(lang, s), &[("app", APP_NAME)]); let about = take(&mut bar, |n| matches!(n, Node::Item(it) if it.role == Some(ItemRole::About))); @@ -406,7 +416,7 @@ pub fn mac_layout(bar: &MenuBar, lang: Lang) -> Layout { } if let Some(s) = settings { let own = node_ids(&s); - let comma = bound.get("Cmd+,").filter(|cmd| !own.contains(*cmd)).cloned(); + let comma = comma_owners.iter().find(|id| !own.contains(*id)).cloned(); menu.push(settings_node(s, comma, lang, &mut clashes)); } menu.extend(appearance); @@ -495,9 +505,14 @@ fn settings_node(node: Node, comma_taken: Option, lang: Lang, clashes: & if let Some(command) = &comma_taken { clashes.push(Clash { shortcut: "Cmd+,", system: "Settings", command: command.clone(), resolution: "Settings has no shortcut" }); } + // Another command's ⌘, wins: Settings drops the key even when it is Settings' own default. let give = |it: &mut Item| { - if comma_taken.is_none() && it.shortcut.is_none() { - it.shortcut = Some("Cmd+,".into()); + if comma_taken.is_none() { + if it.shortcut.is_none() { + it.shortcut = Some("Cmd+,".into()); + } + } else if it.shortcut.as_deref().and_then(Chord::parse).is_some_and(|c| c.portable() == "Cmd+,") { + it.shortcut = None; } }; match node { @@ -623,6 +638,42 @@ pub fn photocraft_layout(items: &[MenuItem], lang: Lang, language: &str) -> Layo layout } +/// Build native menus against effective dispatch ownership, including alternate shortcuts +/// and commands without menu items. AppKit must not consume a saved creative shortcut. +pub fn app_layout(app: &PhotocraftApp, items: &[MenuItem], lang: Lang, language: &str) -> Layout { + fn clear(nodes: &mut [Node], key: &str, owner: &str, lang: Lang) { + let parsed = crate::shortcuts::parse(key); + for node in nodes { + match node { + Node::Item(it) if it.id != owner && it.shortcut.as_deref().and_then(crate::shortcuts::parse) == parsed => it.shortcut = None, + Node::Standard(Standard::Minimize) if key == "Cmd+M" => { + let mut item = Item::new(MINIMIZE, tr(lang, "Minimize")); + item.role = Some(ItemRole::Minimize); + *node = Node::Item(item); + } + Node::Submenu { children, .. } => clear(children, key, owner, lang), + _ => {} + } + } + } + let mut layout = photocraft_layout(items, lang, language); + let bindings = crate::shortcut_dispatch::bindings(app); + for (key, system) in [("Cmd+,", "Settings"), ("Cmd+H", "Hide"), ("Cmd+M", "Minimize"), ("Ctrl+Cmd+H", "Hide"), ("Ctrl+Cmd+M", "Minimize")] { + let parsed = crate::shortcuts::parse(key); + let owner = bindings.iter().find(|(_, sc)| Some(*sc) == parsed).map(|(id, _)| id); + if let Some(command) = owner { + let displayed = layout.bar.find(command).and_then(|it| it.shortcut.as_deref()).and_then(crate::shortcuts::parse); + if displayed != parsed { + for menu in &mut layout.bar.menus { + clear(&mut menu.children, key, command, lang); + } + layout.clashes.push(Clash { shortcut: key, system, command: command.clone(), resolution: "System menu yields to saved command" }); + } + } + } + layout +} + // ----------------------------------------------------------------------------- the app's side /// What the native menu reports. @@ -721,7 +772,7 @@ pub fn sync(app: &mut PhotocraftApp, ctx: &egui::Context) { for it in &mut items { it.enabled &= crate::menus::modal_allows(app, &it.id); } - let layout = photocraft_layout(&items, lang, &app.session.prefs().interface.language); + let layout = app_layout(app, &items, lang, &app.session.prefs().interface.language); let Some(menu) = app.services.native_menu.as_mut() else { return }; if !menu.logged { for c in &layout.clashes { diff --git a/crates/ui-egui/src/menus/native_menu/tests.rs b/crates/ui-egui/src/menus/native_menu/tests.rs index f01d1257f2..ff635b8a24 100644 --- a/crates/ui-egui/src/menus/native_menu/tests.rs +++ b/crates/ui-egui/src/menus/native_menu/tests.rs @@ -69,6 +69,142 @@ fn clashes_are_resolved_in_photocrafts_favour() { assert!(!file.children.contains(&Node::Standard(Standard::CloseWindow)), "⌘W stays File › Close"); } +/// Settings saved on ⌘, (a restored profile) while Hide Layers keeps Photoshop's ⌘,: the menu +/// shows ⌘, once, on Hide Layers, rather than on both. +#[test] +fn a_saved_cmd_comma_on_settings_gives_way_to_hide_layers() { + let mut a = app(true); + // Loaded as saved, not set through Edit › Keyboard Shortcuts (which would clear Hide Layers' row). + a.session.prefs.edit(|p| p.shortcuts.insert("edit.preferences.general".into(), "Cmd+,".into())); + let l = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto"); + let comma: Vec<&str> = l.bar.items().into_iter().filter(|it| it.shortcut.as_deref() == Some("Cmd+,")).map(|it| it.id.as_str()).collect(); + assert_eq!(comma, ["layer.hideLayers"]); + let clash = l.clashes.iter().find(|c| c.shortcut == "Cmd+,").unwrap(); + assert_eq!((clash.command.as_str(), clash.resolution), ("layer.hideLayers", "Settings has no shortcut")); +} + +/// A saved ⌘, on a command with no menu item: the key press runs that command, so the live +/// menu bar must not show ⌘, on Settings. +#[test] +fn a_saved_cmd_comma_without_a_menu_item_takes_the_key_from_settings() { + let mut a = app(true); + a.session.prefs.edit(|p| { + p.shortcuts.insert("edit.fillForeground".into(), "Cmd+,".into()); + // Hide Layers' own default is ⌘,: unbind it so the saved key is the only owner. + p.shortcuts.insert("layer.hideLayers".into(), String::new()); + }); + let items = crate::menus::menu_items(&a); + assert!(!items.iter().any(|it| it.id == "edit.fillForeground"), "the test needs a command with no menu item"); + let comma = crate::shortcuts::parse("Cmd+,"); + let keys = crate::shortcut_dispatch::bindings(&a); + assert_eq!(keys.iter().find(|(_, sc)| Some(*sc) == comma).map(|(id, _)| id.as_str()), Some("edit.fillForeground")); + let l = app_layout(&a, &items, Lang::EN, "auto"); + assert!(l.bar.items().iter().all(|it| it.shortcut.as_deref() != Some("Cmd+,"))); + assert_eq!(l.clashes.iter().find(|c| c.shortcut == "Cmd+,").map(|c| c.command.as_str()), Some("edit.fillForeground")); + // With ⌘, free there is no clash, and Settings keeps Photoshop's ⌘K. + let mut free = app(true); + free.session.prefs.edit(|p| p.shortcuts.insert("layer.hideLayers".into(), String::new())); + let l = app_layout(&free, &crate::menus::menu_items(&free), Lang::EN, "auto"); + assert!(!l.clashes.iter().any(|c| c.shortcut == "Cmd+,")); + assert_eq!(l.bar.find("edit.preferences.general").unwrap().shortcut.as_deref(), Some("Cmd+K")); +} + +#[test] +fn saved_hide_and_minimize_keys_without_menu_items_reach_dispatch() { + for key in ["Cmd+H", "Cmd+M"] { + let mut a = app(true); + a.session.prefs.edit(|p| p.shortcuts.insert("edit.fillForeground".into(), key.into())); + let items = crate::menus::menu_items(&a); + assert!(!items.iter().any(|it| it.id == "edit.fillForeground")); + let parsed = crate::shortcuts::parse(key); + assert_eq!(crate::shortcut_dispatch::bindings(&a).iter().find(|(_, sc)| Some(*sc) == parsed).map(|(id, _)| id.as_str()), Some("edit.fillForeground")); + let layout = app_layout(&a, &items, Lang::EN, "auto"); + assert!(layout.bar.items().iter().all(|it| it.shortcut.as_deref().and_then(crate::shortcuts::parse) != parsed)); + assert!(!layout.bar.menu(MenuRole::Window).unwrap().children.contains(&Node::Standard(Standard::Minimize)) || key != "Cmd+M"); + } +} + +#[test] +fn a_saved_alternate_on_a_visible_command_removes_settings_comma() { + let mut a = app(true); + a.session.prefs.edit(|p| p.alternate_shortcuts.insert("view.extras".into(), vec!["Cmd+,".into()])); + let items = crate::menus::menu_items(&a); + assert!(items.iter().any(|it| it.id == "view.extras")); + let comma = crate::shortcuts::parse("Cmd+,"); + assert_eq!(crate::shortcut_dispatch::bindings(&a).iter().find(|(_, sc)| Some(*sc) == comma).map(|(id, _)| id.as_str()), Some("view.extras")); + let layout = app_layout(&a, &items, Lang::EN, "auto"); + assert!(layout.bar.items().iter().all(|it| it.shortcut.as_deref().and_then(crate::shortcuts::parse) != comma)); + assert_eq!(a.session.prefs.get().alternate_shortcuts["view.extras"], ["Cmd+,"]); +} + +/// The same for an item that moves to the app menu ahead of Settings (About). +#[test] +fn a_saved_cmd_comma_on_about_takes_the_key_from_settings() { + let mut a = app(true); + a.session.prefs.edit(|p| { + p.shortcuts.insert("help.about".into(), "Cmd+,".into()); + // As above: Hide Layers' default ⌘, would be a second owner. + p.shortcuts.insert("layer.hideLayers".into(), String::new()); + }); + let l = photocraft_layout(&crate::menus::menu_items(&a), Lang::EN, "auto"); + let comma: Vec<&str> = l.bar.items().into_iter().filter(|it| it.shortcut.as_deref() == Some("Cmd+,")).map(|it| it.id.as_str()).collect(); + assert_eq!(comma, ["help.about"]); + assert_ne!(l.bar.find("edit.preferences.general").unwrap().shortcut.as_deref(), Some("Cmd+,")); + assert_eq!(l.clashes.iter().find(|c| c.shortcut == "Cmd+,").map(|c| c.command.as_str()), Some("help.about")); +} + +/// The default bindings are Photoshop's on every platform: the menu fixes change who shows a +/// key, not which command a key runs. +#[test] +fn photoshop_defaults_hold_on_every_platform() { + let a = app(true); + let keys = crate::shortcut_dispatch::bindings(&a); + let binding = |key: &str| keys.iter().find(|(_, sc)| Some(*sc) == crate::shortcuts::parse(key)).map(|(id, _)| id.as_str()); + assert_eq!(binding("Cmd+K"), Some("edit.preferences.general")); + assert_eq!(binding("Cmd+H"), Some("view.extras")); + assert_eq!(binding("Cmd+M"), Some("image.adjustments.curves")); + assert_eq!(binding("Cmd+,"), Some("layer.hideLayers")); + let l = app_layout(&a, &crate::menus::menu_items(&a), Lang::EN, "auto"); + assert_eq!(l.bar.find(HIDE).unwrap().shortcut.as_deref(), Some("Ctrl+Cmd+H")); + assert_eq!(l.bar.find(MINIMIZE).unwrap().shortcut.as_deref(), Some("Ctrl+Cmd+M")); + assert_eq!(l.bar.find("edit.preferences.general").unwrap().shortcut.as_deref(), Some("Cmd+K")); +} + +/// A Photoshop `.kys` set imported through Edit › Keyboard Shortcuts moves ⌘M to Levels and gives +/// Fill ⌘, as its second key: each key runs the imported command, so ⌘M shows on Levels only, +/// Minimize keeps ⌃⌘M, and Settings drops ⌘, though Fill's row shows its first key. The set's +/// Hide Photoshop row is not ours and changes nothing. +#[test] +fn an_imported_kys_set_owns_the_system_keys_it_binds() { + const SET: &str = "\u{feff} + +\tCmd+M +\tShift+F5Cmd+, +\tCmd+H + +"; + let mut a = app(true); + let r = a.session.execute("edit.keyboardShortcuts", json!({"importKys": SET})).unwrap(); + assert_eq!(r["import"]["unknown"], json!(["Hide Photoshop"]), "{r}"); + let keys = crate::shortcut_dispatch::bindings(&a); + let owner = |key: &str| keys.iter().find(|(_, sc)| Some(*sc) == crate::shortcuts::parse(key)).map(|(id, _)| id.clone()); + assert_eq!(owner("Cmd+M").as_deref(), Some("image.adjustments.levels")); + let fill = owner("Cmd+,").unwrap(); + assert_eq!(fill, "edit.fill"); + let l = app_layout(&a, &crate::menus::menu_items(&a), Lang::EN, "auto"); + let showing = |key: &str| -> Vec { + let parsed = crate::shortcuts::parse(key); + l.bar.items().into_iter().filter(|it| it.shortcut.as_deref().and_then(crate::shortcuts::parse) == parsed).map(|it| it.id.clone()).collect() + }; + assert_eq!(showing("Cmd+M"), ["image.adjustments.levels"]); + assert!(showing("Cmd+,").is_empty(), "{:?}", showing("Cmd+,")); + assert_eq!(l.bar.find(&fill).unwrap().shortcut.as_deref(), Some("Shift+F5")); + assert_eq!(l.bar.find(MINIMIZE).unwrap().shortcut.as_deref(), Some("Ctrl+Cmd+M")); + assert_eq!(l.bar.find(HIDE).unwrap().shortcut.as_deref(), Some("Ctrl+Cmd+H")); + assert_eq!(showing("Cmd+H"), ["view.extras"], "Hide Photoshop was not imported"); + assert!(l.clashes.iter().any(|c| c.shortcut == "Cmd+," && c.command == fill)); +} + /// Themes and the appearance-mode cycle move from Window to the app menu's Appearance. #[test] fn themes_move_to_the_app_menus_appearance() { diff --git a/crates/ui-egui/src/menus/parity.rs b/crates/ui-egui/src/menus/parity.rs index 36a4d7bd28..f320b4a4a4 100644 --- a/crates/ui-egui/src/menus/parity.rs +++ b/crates/ui-egui/src/menus/parity.rs @@ -7,7 +7,7 @@ use crate::menu_catalog::CATALOG; use crate::menus::is_live; /// Minimum number of live catalog items. Raise it when parity grows; never lower it. -pub const FLOOR: usize = 661; +pub const FLOOR: usize = 663; /// One top-level menu's coverage. #[derive(Clone, Debug, serde::Serialize)] diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 2dd79b06b5..1b814c27e1 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -151,6 +151,12 @@ pub(super) fn checked(app: &PhotocraftApp, id: &str) -> Option { if id == "select.isolateLayers" { return Some(app.session.active().is_some_and(|d| !d.isolated_layers.is_empty())); } + // Edit › Transform › Warp carries a check while the active layer is warped (a smart object + // with a stored warp, or a Warp box open), as the reference's does: picking it then edits + // that warp (#9798). + if id == "edit.transform.warp" { + return Some(crate::transform_tool::warps_active_layer(app)); + } if id == "view.proofColors" || id == "view.gamutWarning" { let Some(d) = app.session.active() else { return Some(false) }; let pv = app.session.color.proof(d.doc.id); diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 69399fc068..126a75e00c 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -550,3 +550,55 @@ fn proof_setup_presets_and_checkmarks() { let params = crate::filter_dialog::parse_spec(spec.params); assert!(matches!(¶ms[0].kind, crate::filter_dialog::Kind::Choice { options, .. } if options[0] == "srgb" && !options.iter().any(|v| v.contains('/')))); } + +/// Layer › Copy CSS puts the layer's CSS on the clipboard, as Photoshop's does (#9372). +#[test] +fn copy_css_puts_the_layers_css_on_the_clipboard() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("layer.new.layer", json!({"name": "Box"})).unwrap(); + app.session + .edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(100, 80, 300, 220), &[0.2, 0.4, 0.8, 1.0]); + Ok(()) + }) + .unwrap(); + app.sync_views(); + assert!(crate::menus::menu_items(&app).iter().any(|i| i.id == "layer.copyCSS" && i.path == ["Layer"]), "Layer › Copy CSS"); + let ctx = egui::Context::default(); + let mut result = None; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + result = Some(invoke(&mut app, ui.ctx(), "layer.copyCSS", json!({}))); + }); + out.textures_delta.clear(); + let css = result.unwrap().unwrap()["css"].as_str().unwrap().to_string(); + assert!(css.starts_with(".Box {\n background-image: url(\"Box.png\");\n"), "{css}"); + assert_eq!(out.platform_output.commands, [egui::OutputCommand::CopyText(css)]); +} + +/// Edit › Transform › Warp is checked while the active layer is warped, as the reference's is: +/// a smart object with a stored warp, or a Warp box open (#9798). +#[test] +fn transform_warp_is_checked_for_a_warped_layer() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + assert_eq!(checked(&app, "edit.transform.warp"), Some(false), "no document"); + app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.sync_views(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(8, 8, 32, 32), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + assert_eq!(checked(&app, "edit.transform.warp"), Some(false), "a plain layer"); + let ctx = egui::Context::default(); + crate::transform_tool::begin_warp(&mut app, &ctx).unwrap(); + assert_eq!(checked(&app, "edit.transform.warp"), Some(true), "a Warp box is open"); + crate::transform_tool::cancel(&mut app); + assert_eq!(checked(&app, "edit.transform.warp"), Some(false)); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + assert_eq!(checked(&app, "edit.transform.warp"), Some(false), "a smart object without a warp"); + app.run("layer.smartObjects.warp", json!({"style": "cylinder", "values": [8, 32, 32, 8, 0.5, 0.5, 0.85], "rect": [8, 8, 32, 32]})).unwrap(); + assert_eq!(checked(&app, "edit.transform.warp"), Some(true), "a stored warp"); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 16cefbd87b..b2b7d56158 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -345,6 +345,7 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para let dialog = |app: &mut PhotocraftApp, fields: Value, choices: Value| Some(Ok(json!({"dialog": form(app, id, label, fields, choices)}))); match id { "file.openAs" => Some(app.open_dialog_file()), + "file.openAsSmartObject" => Some(app.open_dialog_as_smart_object()), "file.openExrParts" => open_exr_parts_dialog(app), "file.saveACopy" => Some(save_a_copy(app)), "file.placeEmbedded" | "file.placeLinked" => { diff --git a/crates/ui-egui/src/menus/view_cmds/dispatch.rs b/crates/ui-egui/src/menus/view_cmds/dispatch.rs index f1e9b2770f..aef68d2dd6 100644 --- a/crates/ui-egui/src/menus/view_cmds/dispatch.rs +++ b/crates/ui-egui/src/menus/view_cmds/dispatch.rs @@ -223,6 +223,7 @@ fn wraps(id: &str) -> bool { matches!( id, "file.openAs" + | "file.openAsSmartObject" | "file.openExrParts" | "file.saveACopy" | "file.placeEmbedded" diff --git a/crates/ui-egui/src/mixer_blend_combination_tests.rs b/crates/ui-egui/src/mixer_blend_combination_tests.rs new file mode 100644 index 0000000000..2b4cd12782 --- /dev/null +++ b/crates/ui-egui/src/mixer_blend_combination_tests.rs @@ -0,0 +1,171 @@ +//! The Mixer Brush's Useful mixer brush combinations dropdown (#11946): between the Clean after +//! each stroke toggle and Wet, Custom then the reference's twelve entries in four groups; each +//! sets Wet, Load and Mix in one `tools.setBrush` change and leaves Flow. Reset Tool shows Custom. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::{MIXER_COMBINATION_GROUPS, MIXER_COMBINATIONS}; +use crate::PhotocraftApp; +use crate::state::Tool; + +const TIP: &str = "Useful mixer brush combinations"; + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.ui.tool = Tool::MixerBrush; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"mixer": {"flow": 0.42}}})).unwrap(); + let mut h = Harness::builder().with_size(vec2(1800.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + h +} + +fn has_fonts(h: &Harness<'static, PhotocraftApp>) -> bool { + h.ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) +} + +/// The combinations dropdown, by the entry it shows. +fn dropdown_rect(h: &Harness<'static, PhotocraftApp>, shows: &str) -> egui::Rect { + h.get_all_by_role(egui::accesskit::Role::ComboBox) + .find(|n| n.accesskit_node().value().as_deref() == Some(shows)) + .unwrap_or_else(|| panic!("no dropdown showing {shows}")) + .rect() +} + +fn open_and_pick(h: &mut Harness<'static, PhotocraftApp>, shows: &str, entry: &str) { + h.get_all_by_role(egui::accesskit::Role::ComboBox).find(|n| n.accesskit_node().value().as_deref() == Some(shows)).unwrap().click(); + h.run_steps(3); + entry_node(h, entry).click(); + h.run_steps(3); +} + +/// An entry of the open list (not the Wet field, which shares the "Wet" label). +fn entry_node<'a>(h: &'a Harness<'static, PhotocraftApp>, entry: &'a str) -> egui_kittest::Node<'a> { + h.get_all_by_label(entry).rfind(|n| n.accesskit_node().role() != egui::accesskit::Role::SpinButton).unwrap_or_else(|| panic!("no entry {entry}")) +} + +fn mixer(h: &Harness<'static, PhotocraftApp>) -> (f32, f32, f32, f32) { + let m = &h.state().session.tools.brush.mixer; + (m.wet, m.load, m.mix, m.flow) +} + +fn set_brush_count(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.journal.iter().filter(|(id, _)| id == "tools.setBrush").count() +} + +#[test] +fn the_dropdown_sits_before_wet_with_the_reference_entries_in_order() { + let mut h = harness(); + if !has_fonts(&h) { + return; + } + let combo = dropdown_rect(&h, "Custom"); + let clean = h.get_by_label("Clean the brush after each stroke").rect(); + let wet = h.get_all_by_role(egui::accesskit::Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Wet")).unwrap().rect(); + assert!(clean.right() <= combo.left() && combo.right() <= wet.left(), "clean {clean:?}, dropdown {combo:?}, wet {wet:?}"); + assert_eq!( + h.get_all_by_role(egui::accesskit::Role::ComboBox) + .find(|n| n.accesskit_node().value().as_deref() == Some("Custom")) + .unwrap() + .accesskit_node() + .label() + .as_deref(), + Some(TIP) + ); + let labels: Vec<&str> = MIXER_COMBINATIONS.iter().map(|(l, _)| *l).collect(); + assert_eq!( + labels, + [ + "Custom", + "Dry", + "Dry, Light Load", + "Dry, Heavy Load", + "Moist", + "Moist, Light Mix", + "Moist, Heavy Mix", + "Wet", + "Wet, Light Mix", + "Wet, Heavy Mix", + "Very Wet", + "Very Wet, Light Mix", + "Very Wet, Heavy Mix" + ] + ); + // Separators above Dry, Moist, Wet and Very Wet. + let groups: Vec<&str> = MIXER_COMBINATION_GROUPS.iter().map(|&i| MIXER_COMBINATIONS[i].0).collect(); + assert_eq!(groups, ["Dry", "Moist", "Wet", "Very Wet"]); + // The open list shows the entries top to bottom in that order. + h.get_all_by_role(egui::accesskit::Role::ComboBox).find(|n| n.accesskit_node().value().as_deref() == Some("Custom")).unwrap().click(); + h.run_steps(3); + let tops: Vec = labels[1..].iter().map(|l| entry_node(&h, l).rect().top()).collect(); + assert!(tops.windows(2).all(|w| w[0] < w[1]), "entries out of order: {tops:?}"); +} + +#[test] +fn each_entry_sets_wet_load_and_mix_in_one_change_and_keeps_flow() { + let mut h = harness(); + if !has_fonts(&h) { + return; + } + let expected = [ + ("Dry", (0.0, 0.5, 0.0)), + ("Dry, Light Load", (0.0, 0.05, 0.0)), + ("Dry, Heavy Load", (0.0, 1.0, 0.0)), + ("Moist", (0.1, 0.05, 0.5)), + ("Moist, Light Mix", (0.1, 0.05, 0.0)), + ("Moist, Heavy Mix", (0.1, 0.05, 1.0)), + ("Wet", (0.5, 0.5, 0.5)), + ("Wet, Light Mix", (0.5, 0.5, 0.0)), + ("Wet, Heavy Mix", (0.5, 0.5, 1.0)), + ("Very Wet", (1.0, 0.5, 0.5)), + ("Very Wet, Light Mix", (1.0, 0.5, 0.0)), + ("Very Wet, Heavy Mix", (1.0, 0.5, 1.0)), + ]; + let mut shows = "Custom"; + for (entry, (wet, load, mix)) in expected { + let before = set_brush_count(&h); + open_and_pick(&mut h, shows, entry); + assert_eq!(mixer(&h), (wet, load, mix, 0.42), "{entry}"); + assert_eq!(set_brush_count(&h), before + 1, "{entry}: one tools.setBrush change"); + assert_eq!(h.state().ui.tool_options.mixer_combination, MIXER_COMBINATIONS.iter().position(|(l, _)| *l == entry).unwrap()); + dropdown_rect(&h, entry); + shows = entry; + } +} + +#[test] +fn reset_tool_shows_custom_and_a_typed_value_keeps_the_pick() { + let mut h = harness(); + if !has_fonts(&h) { + return; + } + open_and_pick(&mut h, "Custom", "Wet, Heavy Mix"); + // A typed Wet keeps showing the picked entry (not measured; today's behaviour). + h.get_all_by_role(egui::accesskit::Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(50.0)).expect("Wet field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text("30".into())); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(mixer(&h).0, 0.3); + dropdown_rect(&h, "Wet, Heavy Mix"); + // Reset Tool: Custom again. + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(h.state().ui.tool_options.mixer_combination, 0); + dropdown_rect(&h, "Custom"); +} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 0d40e2280b..4705eb5b64 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -72,14 +72,19 @@ pub(crate) use color::{color_field, color_field_fill_id, field_chips, field_hsva pub(crate) use color::{hsva_color32, hsva_srgb, srgb_bytes}; #[cfg(test)] pub(crate) use dock::DOCK_MIN_WIDTH; +#[cfg(test)] +pub(crate) use dock::dock_panel_width; pub(crate) use dock::{canvas_panel, dock_body, dock_width_id, dock_width_range}; -pub use dock::{dock_area, request_dock_width}; +pub(crate) use dock::{clear_dock_edge_drag, dock_edge_drag_active}; +pub use dock::{dock_area, dock_panel, request_dock_width}; #[cfg(test)] use history::history; #[cfg(test)] pub(crate) use history::select_snapshot; pub(crate) use history::selected_snapshot; #[cfg(test)] +pub(crate) use history::step_icon as history_step_icon; +#[cfg(test)] use info::info_panel; pub(crate) use info::{SamplerReadouts, sampler_readouts}; #[cfg(test)] diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 73675c83f6..3ecc6708b0 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -1703,7 +1703,12 @@ fn duplicate_selection(app: &mut PhotocraftApp) -> Result { return Ok(result); } let action = app.ui.actions.selected.ok_or_else(|| tl!("Select an action first").to_string())?; - let step = app.ui.actions.selected_step; + duplicate_row(app, action, app.ui.actions.selected_step) +} + +/// Duplicate one action or step (the selected row, or one dropped on Create new action, #12373) +/// and select the copy. +fn duplicate_row(app: &mut PhotocraftApp, action: usize, step: Option) -> Result { let count = app.session.actions.list.len(); let expanded = app.ui.actions.expanded.get(action).copied().unwrap_or(false); let result = app.run("actions.duplicate", json!({"action": action, "step": step}))?; @@ -1715,6 +1720,10 @@ fn duplicate_selection(app: &mut PhotocraftApp) -> Result { if index <= app.ui.actions.expanded.len() { app.ui.actions.expanded.insert(index, expanded); } + // A name field open on an action at or after the copy moves down with that action. + if let Some(r) = app.ui.actions.renaming.as_mut().filter(|r| r.index >= index) { + r.index += 1; + } } else { app.ui.actions.expanded.resize(count, false); if let Some(expanded) = app.ui.actions.expanded.get_mut(index) { @@ -1727,19 +1736,65 @@ fn duplicate_selection(app: &mut PhotocraftApp) -> Result { fn delete_selection(app: &mut PhotocraftApp) { let Some(action) = app.ui.actions.selected else { return }; let step = app.ui.actions.selected_step; - let mut params = json!({"action": action}); - if let Some(step) = step { - params["step"] = json!(step); - } - if app.run("actions.delete", params).is_err() { + if !delete_row(app, action, step) { return; } // Clear selection after deletion so a second click cannot delete a different // step or unexpectedly fall back to deleting the entire action. app.ui.actions.selected = None; app.ui.actions.selected_step = None; - if step.is_none() && action < app.ui.actions.expanded.len() { - app.ui.actions.expanded.remove(action); +} + +/// Delete one action or step (the selected row, or one dropped on the trash, #12373) and keep +/// the selection and disclosure rows pointing at the same rows. False when the engine refused. +fn delete_row(app: &mut PhotocraftApp, action: usize, step: Option) -> bool { + let mut params = json!({"action": action}); + if let Some(step) = step { + params["step"] = json!(step); + } + if app.run("actions.delete", params).is_err() { + return false; + } + let ui = &mut app.ui.actions; + match (step, ui.selected) { + (None, Some(sel)) if sel == action => { + ui.selected = None; + ui.selected_step = None; + } + (None, Some(sel)) if sel > action => ui.selected = Some(sel - 1), + (Some(step), Some(sel)) if sel == action => match ui.selected_step { + Some(s) if s == step => { + ui.selected = None; + ui.selected_step = None; + } + Some(s) if s > step => ui.selected_step = Some(s - 1), + _ => {} + }, + _ => {} + } + if step.is_none() { + if action < ui.expanded.len() { + ui.expanded.remove(action); + } + // A name field open on the deleted action closes; one on a later action moves up with it. + match ui.renaming.as_ref().map(|r| r.index) { + Some(i) if i == action => ui.renaming = None, + Some(i) if i > action => { + if let Some(r) = ui.renaming.as_mut() { + r.index = i - 1; + } + } + _ => {} + } + } + true +} + +/// Outline a footer button a dragged row would be dropped on (an outline only, so the icon +/// stays visible). +fn drop_target_highlight(ui: &egui::Ui, response: &egui::Response, active: bool, t: &Tokens) { + if active && response.contains_pointer() { + ui.painter().rect_stroke(response.rect, t.radius_sm, Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); } } @@ -2153,16 +2208,34 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.status = e; app.ui.status_error = true; } - if crate::icons::button(ui, "plus", 24.0, false, tl!("Create new action")).clicked() && !recording_now { + let dragged = egui::DragAndDrop::payload::(ui.ctx()).map(|row| *row); + let plus = crate::icons::button(ui, "plus", 24.0, false, tl!("Create new action")); + if plus.clicked() && !recording_now { begin_recording(app, false); } + // A row dragged onto Create new action is duplicated, as in Photoshop (#12373). + drop_target_highlight(ui, &plus, dragged.is_some() && !recording_now, &t); + if !recording_now + && let Some(row) = plus.dnd_release_payload::() + && let Err(e) = duplicate_row(app, row.action, row.step) + { + app.ui.status = e; + app.ui.status_error = true; + } let can_delete = app.ui.actions.selected.is_some() && (!recording_now || app.ui.actions.selected_step.is_some()); - ui.add_enabled_ui(can_delete, |ui| { + // While recording only a step may be deleted, by the button or by a drop. + let can_drop = dragged.is_some_and(|row| !recording_now || row.step.is_some()); + ui.add_enabled_ui(can_delete || can_drop, |ui| { let response = crate::icons::button(ui, "trash", 24.0, false, tl!("Delete")); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, can_delete, tl!("Delete"))); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, can_delete || can_drop, tl!("Delete"))); if response.clicked() { delete_selection(app); } + // A row dragged onto the trash is deleted without a confirmation (#12373). + drop_target_highlight(ui, &response, can_drop, &t); + if can_drop && let Some(row) = response.dnd_release_payload::() { + delete_row(app, row.action, row.step); + } }); let mode_label = if app.ui.actions.button_mode { tl!("Button Mode On") } else { tl!("Button Mode") }; let mode_button = ui.add_enabled(!recording_now, egui::Button::new(mode_label).small()).on_hover_text(tl!("Button Mode")); @@ -2293,3 +2366,6 @@ mod stop_tests; #[cfg(test)] mod playback_tests; + +#[cfg(test)] +mod drag_drop_tests; diff --git a/crates/ui-egui/src/panels/actions/drag_drop_tests.rs b/crates/ui-egui/src/panels/actions/drag_drop_tests.rs new file mode 100644 index 0000000000..2c89514886 --- /dev/null +++ b/crates/ui-egui/src/panels/actions/drag_drop_tests.rs @@ -0,0 +1,139 @@ +//! #12373: an Actions panel row dragged onto the trash is deleted, onto Create new action duplicated. +use super::*; +use egui_kittest::{Harness, kittest::Queryable}; + +fn names(app: &PhotocraftApp) -> Vec { + app.session.actions.list.iter().map(|a| a.name.clone()).collect() +} + +fn steps(app: &PhotocraftApp, action: usize) -> Vec { + app.session.actions.list[action].steps.iter().map(|s| s.0.clone()).collect() +} + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.actions.list.push(Action { + name: "First".into(), + steps: vec![("view.zoomOut".into(), json!({})), ("view.fitOnScreen".into(), json!({})), ("view.actualPixels".into(), json!({}))], + ..Default::default() + }); + app.session.actions.list.push(Action { name: "Second".into(), steps: vec![("view.zoomIn".into(), json!({}))], ..Default::default() }); + app.ui.actions.expanded = vec![true, false]; + let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(4); + h +} + +fn drag(h: &mut Harness<'_, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2) { + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(from + vec2(10.0, 0.0))); + h.run_steps(2); + h.event(egui::Event::PointerMoved(to)); + h.run_steps(2); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); +} + +fn center(h: &Harness<'_, PhotocraftApp>, label: &str) -> egui::Pos2 { + h.get_by_label(label).rect().center() +} + +#[test] +fn step_dragged_onto_trash_deletes_only_that_step() { + let mut h = harness(); + let (from, to) = (center(&h, "Fit on Screen"), center(&h, "Delete")); + drag(&mut h, from, to); + assert_eq!(names(h.state()), ["First", "Second"]); + assert_eq!(steps(h.state(), 0), ["view.zoomOut", "view.actualPixels"]); +} + +#[test] +fn action_dragged_onto_trash_is_deleted_even_when_another_is_selected() { + let mut h = harness(); + h.state_mut().ui.actions.select(1, None); + h.run_steps(2); + let (from, to) = (center(&h, "First"), center(&h, "Delete")); + drag(&mut h, from, to); + assert_eq!(names(h.state()), ["Second"]); + assert_eq!(h.state().ui.actions.selected, Some(0)); + assert_eq!(h.state().ui.actions.expanded.len(), 1); +} + +#[test] +fn action_dragged_onto_plus_adds_a_copy_after_it() { + let mut h = harness(); + let (from, to) = (center(&h, "First"), center(&h, "Create new action")); + drag(&mut h, from, to); + assert_eq!(names(h.state()).len(), 3); + assert_eq!(names(h.state())[0], "First"); + assert_eq!(names(h.state())[2], "Second"); + assert_eq!(steps(h.state(), 1), steps(h.state(), 0)); + assert!(h.state().session.actions.recording.is_none()); +} + +#[test] +fn step_dragged_onto_plus_duplicates_the_step_in_place() { + let mut h = harness(); + let (from, to) = (center(&h, "Fit on Screen"), center(&h, "Create new action")); + drag(&mut h, from, to); + assert_eq!(names(h.state()), ["First", "Second"]); + assert_eq!(steps(h.state(), 0), ["view.zoomOut", "view.fitOnScreen", "view.fitOnScreen", "view.actualPixels"]); +} + +#[test] +fn drag_released_over_empty_space_changes_nothing() { + let mut h = harness(); + let from = center(&h, "Fit on Screen"); + drag(&mut h, from, pos2(160.0, 300.0)); + assert_eq!(names(h.state()), ["First", "Second"]); + assert_eq!(steps(h.state(), 0).len(), 3); + assert_eq!(steps(h.state(), 1).len(), 1); +} + +#[test] +fn action_dropped_on_trash_while_recording_is_not_deleted() { + let mut h = harness(); + h.state_mut().run("actions.record", json!({"name": "Rec"})).unwrap(); + h.run_steps(3); + let (from, to) = (center(&h, "Second"), center(&h, "Delete")); + drag(&mut h, from, to); + assert!(names(h.state()).contains(&"Second".to_string())); + assert!(names(h.state()).contains(&"First".to_string())); +} + +fn rename_open_on(app: &mut PhotocraftApp, index: usize, text: &str) { + app.ui.actions.renaming = Some(RenameAction { index, text: text.into(), focused: true }); +} + +fn renaming(app: &PhotocraftApp) -> Option<(usize, String)> { + app.ui.actions.renaming.as_ref().map(|r| (r.index, r.text.clone())) +} + +#[test] +fn an_open_name_field_stays_on_its_action_when_another_is_deleted_or_copied() { + let mut h = harness(); + let app = h.state_mut(); + // Deleting the action above moves the field up with its action. + rename_open_on(app, 1, "Second renamed"); + assert!(delete_row(app, 0, None)); + assert_eq!(renaming(app), Some((0, "Second renamed".into()))); + // Deleting the action being renamed closes the field. + assert!(delete_row(app, 0, None)); + assert_eq!(renaming(app), None); + + let mut h = harness(); + let app = h.state_mut(); + // A copy inserted above moves the field down with its action; one below leaves it. + rename_open_on(app, 1, "Second renamed"); + duplicate_row(app, 0, None).unwrap(); + assert_eq!(renaming(app), Some((2, "Second renamed".into()))); + duplicate_row(app, 2, None).unwrap(); + assert_eq!(renaming(app), Some((2, "Second renamed".into()))); + // Deleting or copying a step leaves it alone. + assert!(delete_row(app, 0, Some(0))); + duplicate_row(app, 0, Some(0)).unwrap(); + assert_eq!(renaming(app), Some((2, "Second renamed".into()))); +} diff --git a/crates/ui-egui/src/panels/blend_preview.rs b/crates/ui-egui/src/panels/blend_preview.rs index 37617ea6cf..e53a22b351 100644 --- a/crates/ui-egui/src/panels/blend_preview.rs +++ b/crates/ui-egui/src/panels/blend_preview.rs @@ -51,7 +51,8 @@ pub(crate) fn hover(app: &mut PhotocraftApp, layers: &[LayerId], mode: Option = Some(Rect::EMPTY); for &id in layers { - area = match (area, photocraft_compose::change_bounds(st.doc.layer(id)?, st.doc.bounds())) { + st.doc.layer(id)?; + area = match (area, photocraft_compose::layer_change_bounds(&st.doc, id)) { (Some(a), Some(b)) => Some(if a.is_empty() { b } else { a.union(&b) }), _ => None, }; diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index ddd45f38ba..fc8e28996d 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -35,6 +35,18 @@ pub(super) fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraf } } +/// The Eraser's Smoothing %: whole numbers 0..100 that say when a typed value was past them, for +/// the reference's alert (#11938). Returns the field and whether to show the alert. +pub(super) fn smoothing_field_alerting(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings, width: f32) -> (egui::Response, bool) { + let mut sm = b.smoothing.amount * 100.0; + let (r, alert) = widgets::value_field_whole_alerting(ui, tl!("Smoothing"), &mut sm, 0.0..=100.0, "%", width); + if r.changed() { + b.smoothing.enabled = true; + b.smoothing.amount = (sm / 100.0).clamp(0.0, 1.0); + } + (r, alert) +} + /// Options-bar Smoothing % (the brush's stroke smoothing; the live stroke and the commit use it). pub(super) fn smoothing_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings, width: f32) -> egui::Response { let mut sm = (b.smoothing.amount * 100.0).round(); @@ -57,13 +69,69 @@ pub(super) fn smoothing_options(ui: &mut egui::Ui, b: &mut photocraft_engine::Br if brush { ui.label(egui::RichText::new(tl!("Smoothing Options")).strong()); } - widgets::checkbox(ui, &mut s.pulled_string, tl!("Pulled String Mode")); - widgets::checkbox(ui, &mut s.catch_up, tl!("Stroke Catch-up")); - widgets::checkbox(ui, &mut s.catch_up_on_end, tl!("Catch-up on Stroke End")); - widgets::checkbox(ui, &mut s.adjust_for_zoom, tl!("Adjust for Zoom")); + // At 0 % there is no smoothing to tune: the four are greyed and keep their values, as in + // the reference application (#11939). Rounded like the Smoothing field, so a value that + // shows as 0 % greys them too. + let on = (s.amount * 100.0).round() > 0.0; + ui.add_enabled_ui(on, |ui| { + widgets::checkbox(ui, &mut s.pulled_string, tl!("Pulled String Mode")); + widgets::checkbox(ui, &mut s.catch_up, tl!("Stroke Catch-up")); + widgets::checkbox(ui, &mut s.catch_up_on_end, tl!("Catch-up on Stroke End")); + widgets::checkbox(ui, &mut s.adjust_for_zoom, tl!("Adjust for Zoom")); + }); }); } +/// A Useful mixer brush combinations entry: its label and the Wet, Load and Mix it sets. +type MixerCombination = (&'static str, Option<(f32, f32, f32)>); + +/// The Mixer Brush's Useful mixer brush combinations, in the reference's order: each entry's label +/// and the Wet, Load and Mix (0..1) it sets. Custom, the first, sets nothing. +pub(crate) const MIXER_COMBINATIONS: [MixerCombination; 13] = [ + ("Custom", None), + ("Dry", Some((0.0, 0.5, 0.0))), + ("Dry, Light Load", Some((0.0, 0.05, 0.0))), + ("Dry, Heavy Load", Some((0.0, 1.0, 0.0))), + ("Moist", Some((0.1, 0.05, 0.5))), + ("Moist, Light Mix", Some((0.1, 0.05, 0.0))), + ("Moist, Heavy Mix", Some((0.1, 0.05, 1.0))), + ("Wet", Some((0.5, 0.5, 0.5))), + ("Wet, Light Mix", Some((0.5, 0.5, 0.0))), + ("Wet, Heavy Mix", Some((0.5, 0.5, 1.0))), + ("Very Wet", Some((1.0, 0.5, 0.5))), + ("Very Wet, Light Mix", Some((1.0, 0.5, 0.0))), + ("Very Wet, Heavy Mix", Some((1.0, 0.5, 1.0))), +]; + +/// The entries of [`MIXER_COMBINATIONS`] a separator line goes above: Dry, Moist, Wet, Very Wet. +const MIXER_COMBINATION_GROUPS: [usize; 4] = [1, 4, 7, 10]; + +/// Mixer Brush: the Useful mixer brush combinations dropdown (#11946). Picking an entry sets Wet, +/// Load and Mix together (Flow stays) and keeps showing it, also after a value is typed; Custom +/// sets nothing. `picked` is the entry shown. +pub(super) fn mixer_combination_dropdown( + ui: &mut egui::Ui, + picked: &mut usize, + m: &mut photocraft_engine::paint::mixer::MixerSettings, +) -> Option { + const ID: &str = "mixer-combination"; + let opts: Vec<(usize, &str)> = MIXER_COMBINATIONS.iter().enumerate().map(|(i, (label, _))| (i, *label)).collect(); + let mut shown = (*picked).min(MIXER_COMBINATIONS.len() - 1); + let chosen = + widgets::dropdown_wheel_grouped(ui, ID, tl!("Useful mixer brush combinations"), &mut shown, &opts, 132.0, |i| MIXER_COMBINATION_GROUPS.contains(i)).0; + if let Some(&i) = chosen.last() { + *picked = i; + if let Some((wet, load, mix)) = MIXER_COMBINATIONS[i].1 { + (m.wet, m.load, m.mix) = (wet, load, mix); + } + } + ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new(ID))) +} + +#[cfg(test)] +#[path = "../mixer_blend_combination_tests.rs"] +mod mixer_blend_combination_tests; + /// Mixer Brush: the Current Brush Load swatch shows the paint the next stroke starts with (an /// empty swatch when the brush is clean). Its menu holds Load Brush and Clean Brush. pub(super) fn mixer_load_swatch(app: &mut PhotocraftApp, ui: &mut egui::Ui) { @@ -139,3 +207,7 @@ pub(super) fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushS } } } + +#[cfg(test)] +#[path = "../smoothing_options_greyed_tests.rs"] +mod smoothing_options_greyed_tests; diff --git a/crates/ui-egui/src/panels/brush_panel.rs b/crates/ui-egui/src/panels/brush_panel.rs index 615610fa15..1aa1028118 100644 --- a/crates/ui-egui/src/panels/brush_panel.rs +++ b/crates/ui-egui/src/panels/brush_panel.rs @@ -98,6 +98,8 @@ pub struct BrushesPanelState { pub show_stroke: bool, /// The Brush Preset picker's cards: show the tip thumbnail. pub show_tip: bool, + /// The Brush Preset picker's search field (its gear menu's Show Search Bar). + pub show_search: bool, /// The Brush Preset picker's cards and the Brushes tab's grid cells and list rows: their size /// scale, from the picker's footer slider (`crate::brush_picker::body`) or the tab's preview-size /// slider. 1 is the standard size; the cards' width, height and @@ -117,6 +119,7 @@ impl Default for BrushesPanelState { show_name: true, show_stroke: true, show_tip: true, + show_search: true, scale: 1.0, } } diff --git a/crates/ui-egui/src/panels/brush_panel/tests.rs b/crates/ui-egui/src/panels/brush_panel/tests.rs index 164443600c..2fc3f16cf1 100644 --- a/crates/ui-egui/src/panels/brush_panel/tests.rs +++ b/crates/ui-egui/src/panels/brush_panel/tests.rs @@ -1877,6 +1877,110 @@ fn checkboxes_show_a_pressed_state_from_their_label() { assert_eq!(fill(&h), Some(widgets::check_box_fill(true, false, &t))); } +#[test] +fn spacing_row_edits_route_only_the_changed_fields_through_the_brush_command() { + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut h = harness(0, 0); + h.state_mut().run("tools.setBrush", json!({"brush": {"spacing": 0.427, "spacingEnabled": false}})).unwrap(); + h.run_steps(2); + let journal = h.state().session.journal.len(); + let spacing = h.state().session.tools.brush.spacing; + let checkbox = h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Spacing"); + checkbox.click(); + h.run_steps(2); + assert!(h.state().session.tools.brush.spacing_enabled); + assert_eq!(h.state().session.tools.brush.spacing, spacing); + assert_eq!(last_journal(h.state()).unwrap().0, "tools.setBrush"); + assert_eq!(last_journal(h.state()).unwrap().1["brush"], json!({"spacingEnabled": true})); + let field = h.query_all_by_role(egui::accesskit::Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(43.0)).unwrap(); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + assert_eq!(h.state().session.tools.brush.spacing, 0.44); + assert_eq!(last_journal(h.state()).unwrap().0, "tools.setBrush"); + assert_eq!(last_journal(h.state()).unwrap().1["brush"], json!({"spacing": 0.44_f32})); + let checkbox = h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Spacing"); + checkbox.click(); + h.run_steps(2); + assert_eq!(last_journal(h.state()).unwrap().1["brush"], json!({"spacingEnabled": false})); + let field = h.query_all_by_role(egui::accesskit::Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(44.0)).unwrap(); + assert!(field.accesskit_node().is_disabled()); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + assert_eq!(h.state().session.tools.brush.spacing, 0.44); + assert_eq!(h.state().session.journal.len(), journal + 3, "disabled input adds no command"); + let checkbox = h.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Spacing"); + checkbox.click(); + h.run_steps(2); + assert_eq!(h.state().session.tools.brush.spacing, 0.44); + assert_eq!(h.state().session.journal.len(), journal + 4); +} + +#[test] +fn scatter_header_edits_route_to_the_correct_brush_block_and_disabled_sections_ignore_input() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + + for section in [2, 4] { + let block = if section == 2 { "scattering" } else { "dualBrush" }; + let mut h = harness(0, section); + let mut initial = json!({}); + initial[block] = if section == 2 { + json!({"enabled": true, "bothAxes": false, "scatter": {"jitter": 2.137, "control": "penPressure"}, "count": 5}) + } else { + json!({"enabled": true, "bothAxes": false, "scatter": 2.137, "count": 7}) + }; + h.state_mut().run("tools.setBrush", json!({"brush": initial})).unwrap(); + h.run_steps(3); + let journal = h.state().session.journal.len(); + let before = h.state().session.tools.brush.clone(); + h.get_by_label("Both Axes").click(); + h.run_steps(2); + let mut expected = json!({}); + expected[block] = json!({"bothAxes": true}); + assert_eq!(last_journal(h.state()).unwrap().0, "tools.setBrush"); + assert_eq!(last_journal(h.state()).unwrap().1["brush"], expected); + let mut after = before; + if section == 2 { + after.scattering.both_axes = true; + } else { + after.dual_brush.both_axes = true; + } + assert_eq!(h.state().session.tools.brush, after, "toggle changes only the matching axis flag"); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(214.0)).unwrap(); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + expected[block] = if section == 2 { json!({"scatter": {"jitter": 2.15_f32}}) } else { json!({"scatter": 2.15_f32}) }; + assert_eq!(last_journal(h.state()).unwrap().1["brush"], expected); + if section == 2 { + after.scattering.scatter.jitter = 2.15; + } else { + after.dual_brush.scatter = 2.15; + } + assert_eq!(h.state().session.tools.brush, after); + assert_eq!(h.state().session.journal.len(), journal + 2); + let mut off = json!({}); + off[block] = json!({"enabled": false}); + h.state_mut().run("tools.setBrush", json!({"brush": off})).unwrap(); + h.run_steps(2); + let before = h.state().session.tools.brush.clone(); + let journal = h.state().session.journal.len(); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(215.0)).unwrap(); + assert!(field.accesskit_node().is_disabled()); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.event(egui::Event::Text("999".into())); + h.key_press(egui::Key::Enter); + h.get_by_label("Both Axes").click(); + h.run_steps(2); + assert_eq!(h.state().session.tools.brush, before, "the disabled header retains both values"); + assert_eq!(h.state().session.journal.len(), journal, "disabled edits add no command"); + } +} + #[test] fn tip_geometry_edits_and_arrow_drag_route_only_changed_fields_through_the_brush_command() { use egui::accesskit::Role; diff --git a/crates/ui-egui/src/panels/brush_sections.rs b/crates/ui-egui/src/panels/brush_sections.rs index 7026f83352..d7c16283fb 100644 --- a/crates/ui-egui/src/panels/brush_sections.rs +++ b/crates/ui-egui/src/panels/brush_sections.rs @@ -54,6 +54,33 @@ fn signed_pct(ui: &mut egui::Ui, label: &str, v: &mut f32, min: f32, max: f32) - changed } +/// The checkbox labels the spacing field; toggling it must retain imported fractional values. +fn spacing_row(ui: &mut egui::Ui, b: &mut BrushSettings) { + let mut percent = (b.spacing * 100.0).round(); + let mut changed = false; + ui.horizontal(|ui| { + widgets::checkbox(ui, &mut b.spacing_enabled, tl!("Spacing")).on_hover_text(tl!("Off: the speed of the pointer sets the spacing")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + changed = ui + .add_enabled_ui(b.spacing_enabled, |ui| widgets::value_field(ui, &mut percent, 1.0..=1000.0, "%", 74.0).accessible_name(tl!("Spacing"))) + .inner + .changed(); + }); + }); + changed |= ui + .add_enabled_ui(b.spacing_enabled, |ui| { + let s = widgets::slider(ui, &mut percent, 1.0..=1000.0, None); + s.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(percent), tl!("Spacing"))); + s + }) + .inner + .changed(); + if changed { + b.spacing = (percent.round() / 100.0).clamp(0.01, 10.0); + } + ui.add_space(4.0); +} + fn num(ui: &mut egui::Ui, label: &str, v: &mut f32, range: std::ops::RangeInclusive, suffix: &str) -> bool { let mut x = *v; let changed = widgets::slider_row(ui, label, &mut x, range.clone(), suffix, None).changed(); @@ -186,8 +213,9 @@ pub fn ellipse_drag(grab: EllipseGrab, rel: egui::Vec2, angle: f32, roundness: f } } -/// Photoshop's angle/roundness widget: drag the arrow to rotate, the dots to squash. -fn ellipse_widget(ui: &mut egui::Ui, angle: &mut f32, roundness: &mut f32) -> bool { +/// Photoshop's angle/roundness widget: drag the arrow to rotate, the dots to squash. Also at the +/// Brush Preset picker's top left (#11821). +pub(crate) fn ellipse_widget(ui: &mut egui::Ui, angle: &mut f32, roundness: &mut f32) -> bool { let t = Tokens::get(ui.ctx()); let (rect, resp) = ui.allocate_exact_size(vec2(84.0, 84.0), Sense::click_and_drag()); let c = rect.center(); @@ -355,11 +383,7 @@ fn tip_shape(ui: &mut egui::Ui, b: &mut BrushSettings, presets: &[BrushPreset], ui.add_enabled_ui(matches!(b.tip, TipShape::Round), |ui| { pct(ui, tl!("Hardness"), &mut b.hardness, 1.0); }); - // Unchecked, the pointer's speed sets the spacing (Photoshop). - widgets::checkbox(ui, &mut b.spacing_enabled, tl!("Spacing")).on_hover_text(tl!("Off: the speed of the pointer sets the spacing")); - ui.add_space(2.0); - let on = b.spacing_enabled; - ui.add_enabled_ui(on, |ui| signed_pct(ui, tl!("Spacing"), &mut b.spacing, 0.01, 10.0)); + spacing_row(ui, b); None } @@ -383,10 +407,35 @@ fn shape_dynamics(ui: &mut egui::Ui, b: &mut BrushSettings) { widgets::checkbox(ui, &mut sd.brush_projection, tl!("Brush Projection")).on_hover_text(tl!("Apply the pen's tilt and rotation to the tip shape")); } +/// Both scatter controls put their axis switch between the label and percentage field. +fn scatter_row(ui: &mut egui::Ui, amount: &mut f32, both_axes: &mut bool) { + let t = Tokens::get(ui.ctx()); + let mut percent = (*amount * 100.0).round(); + let mut changed = false; + let label = ui + .horizontal(|ui| { + let label = ui.label(RichText::new(tl!("Scatter")).color(t.text_dim)); + widgets::scrub_label_within(ui, &label, f32::INFINITY); + widgets::checkbox(ui, both_axes, tl!("Both Axes")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + changed = widgets::value_field(ui, &mut percent, 0.0..=1000.0, "%", 74.0).changed(); + }); + label.id + }) + .inner; + // Named by its caption, like every `slider_row` slider. + let slider = widgets::slider(ui, &mut percent, 0.0..=1000.0, None); + slider.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(percent), tl!("Scatter"))); + changed |= slider.labelled_by(label).changed(); + if changed { + *amount = (percent.round() / 100.0).clamp(0.0, 10.0); + } + ui.add_space(4.0); +} + fn scattering(ui: &mut egui::Ui, b: &mut BrushSettings) { let sc = &mut b.scattering; - pct(ui, tl!("Scatter"), &mut sc.scatter.jitter, 10.0); - widgets::checkbox(ui, &mut sc.both_axes, tl!("Both Axes")); + scatter_row(ui, &mut sc.scatter.jitter, &mut sc.both_axes); ui.add_space(2.0); control_row(ui, "brush-scatter-ctl", &mut sc.scatter, false); ui.add_space(6.0); @@ -528,8 +577,7 @@ fn dual_brush(ui: &mut egui::Ui, b: &mut BrushSettings, presets: &[BrushPreset]) let orig = d.tip.bitmap_size().map(|(w, h)| w.max(h) as f32); size_row(ui, tl!("Size"), &mut d.size, 2500.0, orig); signed_pct(ui, tl!("Spacing"), &mut d.spacing, 0.01, 10.0); - pct(ui, tl!("Scatter"), &mut d.scatter, 10.0); - widgets::checkbox(ui, &mut d.both_axes, tl!("Both Axes")); + scatter_row(ui, &mut d.scatter, &mut d.both_axes); ui.add_space(4.0); let mut c = d.count as f32; if num(ui, tl!("Count"), &mut c, 1.0..=16.0, "") { diff --git a/crates/ui-egui/src/panels/brush_sections/tests.rs b/crates/ui-egui/src/panels/brush_sections/tests.rs index abed333e02..96338c3464 100644 --- a/crates/ui-egui/src/panels/brush_sections/tests.rs +++ b/crates/ui-egui/src/panels/brush_sections/tests.rs @@ -340,6 +340,170 @@ fn ellipse_widget_drags_angle_and_roundness() { assert_eq!(r, 1.0); } +#[test] +fn spacing_row_has_one_label_and_a_shared_header_in_every_theme() { + for kind in theme::ThemeKind::ALL { + for enabled in [false, true] { + let b = BrushSettings { spacing: 0.427, spacing_enabled: enabled, ..Default::default() }; + let mut h = section_harness(0, b.clone()); + crate::PhotocraftApp::setup_context(&h.ctx, kind); + h.run_steps(3); + assert_eq!(h.query_all_by_role_and_label(Role::Label, "Spacing").count(), 0, "{kind:?}: the checkbox is the single label"); + assert_eq!(h.query_all_by_role_and_label(Role::CheckBox, "Spacing").count(), 1); + let checkbox = h.get_by_role_and_label(Role::CheckBox, "Spacing").rect(); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(43.0)).unwrap(); + assert!((checkbox.center().y - field.rect().center().y).abs() < 2.0, "{kind:?}: checkbox and percentage share a row"); + assert_eq!(field.accesskit_node().is_disabled(), !enabled); + let slider = h.get_by_role_and_label(Role::Slider, "Spacing"); + assert_eq!(slider.accesskit_node().numeric_value(), Some(43.0), "{kind:?}: the track is a named slider"); + assert_eq!(slider.accesskit_node().is_disabled(), !enabled); + assert_eq!(h.state(), &b, "rendering does not round the saved spacing"); + } + } +} + +fn check_scatter_header(section: usize) { + for kind in theme::ThemeKind::ALL { + for both_axes in [false, true] { + let mut b = BrushSettings::default(); + b.scattering.scatter.jitter = 2.137; + b.scattering.both_axes = both_axes; + b.dual_brush.scatter = 2.137; + b.dual_brush.both_axes = both_axes; + let mut h = section_harness(section, b.clone()); + crate::PhotocraftApp::setup_context(&h.ctx, kind); + h.run_steps(3); + let label = caption_rect(&h, "Scatter"); + let axes = h.get_by_label("Both Axes").rect(); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(214.0)).unwrap().rect(); + assert!((label.center().y - axes.center().y).abs() < 2.0, "{kind:?}, section {section}: axes belongs on the Scatter header"); + assert!((axes.center().y - field.center().y).abs() < 2.0, "{kind:?}, section {section}: axes and percentage share a row"); + assert!(label.right() < axes.left() && axes.right() < field.left(), "{kind:?}, section {section}: label, checkbox, percentage order"); + assert_eq!( + h.query_all_by_role_and_label(Role::Slider, "Scatter").count(), + 1, + "{kind:?}, section {section}: the slider is named by its caption, like other slider rows" + ); + assert_eq!(h.state(), &b, "rendering retains fractional scatter and other settings"); + } + } +} + +#[test] +fn spacing_row_retains_disabled_values_and_percentage_editing_limits() { + let mut h = section_harness(0, BrushSettings { spacing: 0.42, spacing_enabled: false, ..Default::default() }); + let before = h.state().clone(); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(42.0)).unwrap(); + let from = pos2(field.rect().left() - 100.0, field.rect().bottom() + 9.0); + let to = pos2(field.rect().right() - 25.0, from.y); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.event(egui::Event::Text("999".into())); + h.key_press(egui::Key::Enter); + h.run_steps(2); + drag(&mut h, from, to); + assert_eq!(h.state(), &before, "Off ignores both field input and a track drag"); + let checkbox = h.get_by_role_and_label(Role::CheckBox, "Spacing"); + checkbox.click(); + h.run_steps(2); + assert!(h.state().spacing_enabled); + assert_eq!(h.state().spacing, 0.42, "enabling keeps the saved value"); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(42.0)).unwrap(); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + assert_eq!(h.state().spacing, 0.43, "integer percentage edits become a fraction"); + drag(&mut h, from, to); + assert!(h.state().spacing > 5.0, "the same track is editable when enabled"); + for (spacing, value, key) in [(0.01, 1.0, egui::Key::ArrowDown), (10.0, 1000.0, egui::Key::ArrowUp)] { + h.state_mut().spacing = spacing; + h.run_steps(2); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(value)).unwrap(); + field.click(); + h.key_press(key); + h.run_steps(2); + assert_eq!(h.state().spacing, spacing, "the percentage stays within 1..1000"); + } +} + +#[test] +fn scatter_header_scattering_places_axes_between_label_and_percentage_in_all_themes() { + check_scatter_header(2); +} + +#[test] +fn scatter_header_dual_brush_places_axes_between_label_and_percentage_in_all_themes() { + check_scatter_header(4); +} + +#[test] +fn scatter_header_preserves_values_percentage_limits_and_label_scrubbing() { + for section in [2, 4] { + let mut b = BrushSettings::default(); + b.scattering.scatter.jitter = 2.137; + b.scattering.scatter.control = Control::PenPressure; + b.scattering.count = 5; + b.dual_brush.scatter = 2.137; + b.dual_brush.count = 7; + let mut h = section_harness(section, b.clone()); + h.get_by_label("Both Axes").click(); + h.run_steps(2); + if section == 2 { + b.scattering.both_axes = true; + } else { + b.dual_brush.both_axes = true; + } + assert_eq!(h.state(), &b, "a toggle does not round scatter or change unrelated fields"); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(214.0)).unwrap(); + field.click(); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + if section == 2 { + b.scattering.scatter.jitter = 2.15; + } else { + b.dual_brush.scatter = 2.15; + } + assert_eq!(h.state(), &b, "percentage edits preserve the other brush block"); + let label = caption_rect(&h, "Scatter").center(); + drag(&mut h, label, label + vec2(18.0, 0.0)); + let amount = if section == 2 { h.state().scattering.scatter.jitter } else { h.state().dual_brush.scatter }; + assert!(amount > 2.15, "the label still scrubs the percentage across the checkbox"); + if section == 2 { + b.scattering.scatter.jitter = amount; + } else { + b.dual_brush.scatter = amount; + } + assert_eq!(h.state(), &b, "scrubbing changes only the scatter amount"); + let field = + h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(f64::from((amount * 100.0).round()))).unwrap(); + let from = pos2(field.rect().left() - 100.0, field.rect().bottom() + 9.0); + let to = pos2(field.rect().right() - 25.0, from.y); + drag(&mut h, from, to); + let amount = if section == 2 { h.state().scattering.scatter.jitter } else { h.state().dual_brush.scatter }; + assert!(amount > 5.0, "the existing amount track remains editable"); + if section == 2 { + b.scattering.scatter.jitter = amount; + } else { + b.dual_brush.scatter = amount; + } + assert_eq!(h.state(), &b); + for (amount, value, key) in [(0.0, 0.0, egui::Key::ArrowDown), (10.0, 1000.0, egui::Key::ArrowUp)] { + if section == 2 { + b.scattering.scatter.jitter = amount; + } else { + b.dual_brush.scatter = amount; + } + *h.state_mut() = b.clone(); + h.run_steps(2); + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().numeric_value() == Some(value)).unwrap(); + field.click(); + h.key_press(key); + h.run_steps(2); + assert_eq!(h.state(), &b, "the percentage stays within 0..1000"); + } + } +} + fn tip_geometry_center(h: &Harness<'static, BrushSettings>) -> egui::Pos2 { fn centre(shape: &egui::Shape) -> Option { match shape { diff --git a/crates/ui-egui/src/panels/brushes_tab/tests.rs b/crates/ui-egui/src/panels/brushes_tab/tests.rs index 81437f53a1..ae654a11e5 100644 --- a/crates/ui-egui/src/panels/brushes_tab/tests.rs +++ b/crates/ui-egui/src/panels/brushes_tab/tests.rs @@ -188,6 +188,8 @@ fn brush_picker_cards_follow_the_part_boxes() { h.state_mut().run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); h.state_mut().ui.tool = crate::state::Tool::Brush; h.state_mut().ui.brush_picker = Some([300.0, 120.0]); + // Every part on (Brush Tip starts off). + h.state_mut().ui.brush_picker_list.show_tip = true; h.run_steps(8); let presets = h.state().session.tools.presets.clone(); let cards = |h: &Harness<'_, PhotocraftApp>| -> Vec { diff --git a/crates/ui-egui/src/panels/dock.rs b/crates/ui-egui/src/panels/dock.rs index 5784e0042d..9613b0e065 100644 --- a/crates/ui-egui/src/panels/dock.rs +++ b/crates/ui-egui/src/panels/dock.rs @@ -19,6 +19,205 @@ pub fn dock_area(app: &mut PhotocraftApp, ui: &mut egui::Ui) { crate::color_panel_ui::persist(app); } +/// The dock and its icon rail as one right panel, for the layout with the toolbox between the +/// canvas and the dock. The canvas is drawn separately afterwards. Keeping the rail inside this +/// panel means the toolbox cannot cover it when it is one column wide. +pub fn dock_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + // Lets the frame tick expire a drag start if this panel stops rendering (dock hidden). + let frame = ui.ctx().cumulative_frame_nr(); + ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("dock-edge-rendered-frame"), frame)); + let t = Tokens::get(ui.ctx()); + let (rail_w, _) = rail_widths(t.pro); + let rail_shown = app.ui.panels.rail; + let rw = if rail_shown { rail_w } else { 0.0 }; + let content = ui.available_rect_before_wrap(); + let range = crate::panels::dock_width_range(content.width()); + // The dock must leave the toolbox and the canvas's 200-point minimum room: the standard + // layout enforces the canvas minimum inside craft-ui, the fixed-size dock-edge panel does not. + let toolbar_w = super::toolbar::toolbar_width(t.pro, app.ui.panels.toolbar_double); + let max_dock = (*range.end()).min((content.width() - toolbar_w - crate::panel_docking::CANVAS_MIN_WIDTH - rw).max(1.0)); + let min_dock = (*range.start()).min(max_dock); + let locked = app.session.prefs().workspace_locked; + let modal = crate::panel_docking::modal_open(app, ui.ctx()); + crate::panel_docking::apply_pending_dock_width(app, ui.ctx()); + let metrics = crate::panel_docking::dock_metrics(app); + let empty = metrics.empty; + if empty { + // Nothing to resize or draw in the dock column, but Studio draws its floating Properties + // group from the docking pass: keep that pass, on the full remaining area, with no column. + if rail_shown { + crate::direction::end_panel("dock-column").resizable(false).show_separator_line(false).exact_size(rw).frame(egui::Frame::NONE.fill(t.chrome)).show( + ui, + |ui| { + ui.spacing_mut().item_spacing.x = 0.0; + let rect = ui.max_rect(); + let inner = rect.shrink2(egui::vec2(4.0, 8.0)); + let mut rail_ui = ui.new_child(egui::UiBuilder::new().max_rect(inner)); + rail_body(app, &mut rail_ui, &t); + }, + ); + } + crate::panels::clear_dock_edge_drag(ui.ctx()); + // A child that does not consume the parent's layout space: the docking pass still draws + // floating windows, but the toolbox and canvas keep their room. + let mut dock_ui = ui.new_child(egui::UiBuilder::new().max_rect(ui.max_rect())); + crate::panel_docking::show_dock(app, &mut dock_ui); + crate::dock::persist(app, ui.ctx()); + crate::color_panel_ui::persist(app); + return; + } + let iconic = metrics.iconic_only; + let natural_min = if iconic { metrics.minimum } else { metrics.minimum.max(min_dock) }; + let max_dock = max_dock.min(if metrics.maximum.is_finite() { metrics.maximum.max(natural_min) } else { max_dock }); + let feasible = natural_min <= max_dock + 0.5; + let min_visible = natural_min.min(max_dock); + // Draw the width the layout actually has, not the minimum the gestures enforce. + let mut stored = metrics.width.clamp(1.0, max_dock); + let generation = app.ui.docking_generation; + let drag_id = egui::Id::unique("dock-edge-drag"); + // Resizing is unavailable while locked, modal, when the parent UI is disabled (screen picking + // disables it), or when the window cannot fit the column minima. A disabled handle never + // receives drag_stopped, so drop any stored start here; a start from another workspace + // generation is stale and must not touch this one. + let resizable = !locked && !modal && ui.is_enabled() && feasible; + let mut drag = match if resizable { ui.ctx().data(|d| d.get_temp::<(f32, f32, u64)>(drag_id)) } else { None } { + Some((start_x, start_w, saved)) if saved == generation => Some((start_x, start_w)), + Some(_) => { + crate::panels::clear_dock_edge_drag(ui.ctx()); + None + } + None => { + if !resizable { + crate::panels::clear_dock_edge_drag(ui.ctx()); + } + None + } + }; + let lower = (min_visible + rw).min(max_dock + rw); + let upper = max_dock + rw; + // A gesture applies its minimum even without motion; idle may retain a narrower saved width. + let pointer_width = |start_x: f32, start_w: f32| { + let pointer = ui.ctx().input(|i| i.pointer.latest_pos()).map_or(start_x, |pos| pos.x); + let dx = if crate::direction::is_rtl() { pointer - start_x } else { start_x - pointer }; + (start_w + dx).clamp(lower, upper) + }; + // The release frame still carries the final pointer position; apply it before dropping the + // drag, so the dock keeps the width the user released at instead of the previous frame's. + if let Some((start_x, start_w)) = drag + && !ui.ctx().input(|i| i.pointer.any_down()) + { + let final_w = pointer_width(start_x, start_w); + let requested = (final_w - rw).clamp(min_visible, max_dock); + stored = crate::panel_docking::set_end_dock_total(app, requested).unwrap_or(requested).clamp(1.0, max_dock); + drag = None; + ui.ctx().data_mut(|d| d.remove::<(f32, f32, u64)>(drag_id)); + } + let mut panel_w = if let Some((start_x, start_w)) = drag { pointer_width(start_x, start_w) } else { stored + rw }; + if drag.is_some() && resizable { + let requested = (panel_w - rw).clamp(min_visible, max_dock); + if let Some(actual) = crate::panel_docking::set_end_dock_total(app, requested) { + // The model can land somewhere other than the pointer request (minimums, iconic + // caps); draw the panel at the width that was actually stored. + panel_w = (actual + rw).clamp(lower, upper); + } + } + let panel = + crate::direction::end_panel("dock-column").resizable(false).show_separator_line(false).exact_size(panel_w).frame(egui::Frame::NONE.fill(t.card)).show( + ui, + |ui| { + ui.spacing_mut().item_spacing.x = 0.0; + let height = ui.available_height(); + let mut dock_rect = ui.max_rect(); + if rail_shown { + // The rail sits between the dock (at the window edge) and the toolbox, with the + // chrome fill and inset the standalone rail panel gives it. + let rail_rect = if crate::direction::is_rtl() { + egui::Rect::from_min_size(egui::pos2(dock_rect.right() - rw, dock_rect.top()), egui::vec2(rw, height)) + } else { + egui::Rect::from_min_size(dock_rect.min, egui::vec2(rw, height)) + }; + ui.painter().rect_filled(rail_rect, 0.0, t.chrome); + ui.allocate_rect(rail_rect, egui::Sense::hover()); + let inner = rail_rect.shrink2(egui::vec2(4.0, 8.0)); + let mut rail_ui = ui.new_child(egui::UiBuilder::new().max_rect(inner)); + rail_body(app, &mut rail_ui, &t); + if crate::direction::is_rtl() { + dock_rect.max.x = rail_rect.left(); + } else { + dock_rect.min.x = rail_rect.right(); + } + } + let mut dock_ui = ui.new_child(egui::UiBuilder::new().max_rect(dock_rect)); + // The docking pass also renders floating windows (Studio floats Properties over the + // canvas), so it runs even when the dock column itself is empty. + crate::panel_docking::show_dock(app, &mut dock_ui); + // Block the docking layout's column-edge handle at the dock's content edge. It is + // registered before the resize handle so the handle wins where they overlap when the + // rail is hidden and both edges coincide; one point either side keeps tab strips and + // scrollbars clear. + let dock_edge = if crate::direction::is_rtl() { dock_rect.right() } else { dock_rect.left() }; + let cover = egui::Rect::from_min_max(egui::pos2(dock_edge - 1.0, dock_rect.top()), egui::pos2(dock_edge + 1.0, dock_rect.bottom())); + let _ = ui.interact(cover, egui::Id::unique("dock-content-edge"), egui::Sense::click_and_drag()); + // The panel's inner edge (between the toolbox and the rail) is the resize handle. + let panel_rect = ui.max_rect(); + let panel_edge = if crate::direction::is_rtl() { panel_rect.right() } else { panel_rect.left() }; + let handle = egui::Rect::from_min_max(egui::pos2(panel_edge - 4.0, panel_rect.top()), egui::pos2(panel_edge + 4.0, panel_rect.bottom())); + // A locked workspace, an empty dock (nothing to resize), a modal dialog or a disabled + // UI leaves the handle inert. + let sense = if resizable { egui::Sense::drag() } else { egui::Sense::hover() }; + let response = ui.interact(handle, egui::Id::unique("dock-edge-handle"), sense); + // The bar is always visible, on the foreground layer so no panel, rail or dock + // content can hide it; it brightens under the pointer. + let active = resizable && (response.hovered() || response.dragged()); + if active { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + let line = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("dock-edge-line")); + // The theme's separator colour at rest, the accent while the edge is hovered or + // dragged: a dark divider that lights up, not a permanently lit bar. + let color = if active { t.accent } else { t.separator }; + ui.ctx().layer_painter(line).vline(panel_edge, panel_rect.y_range(), Stroke::new(1.0, color)); + if response.drag_started() { + let start_x = response.interact_pointer_pos().map_or(panel_edge, |pos| pos.x); + ui.ctx().data_mut(|d| d.insert_temp(drag_id, (start_x, panel_w, generation))); + } + if response.dragged() { + ui.ctx().request_repaint(); + } + if response.drag_stopped() { + ui.ctx().data_mut(|d| d.remove::<(f32, f32, u64)>(drag_id)); + } + }, + ); + crate::panel_docking::record::dock_panel_rect(ui.ctx(), panel.response.rect); + crate::dock::persist(app, ui.ctx()); + crate::color_panel_ui::persist(app); +} + +/// True while the dock-edge resize drag has a stored start: a synthetic/accessibility click can +/// arrive with no pointer button down, but the in-progress dock width must not be persisted. +pub(crate) fn dock_edge_drag_active(ctx: &egui::Context) -> bool { + ctx.data(|data| data.get_temp::<(f32, f32, u64)>(egui::Id::unique("dock-edge-drag")).is_some()) +} + +/// Drops a dock-edge drag start that can no longer be completed (its panel stopped rendering). +pub(crate) fn clear_dock_edge_drag(ctx: &egui::Context) { + ctx.data_mut(|data| data.remove::<(f32, f32, u64)>(egui::Id::unique("dock-edge-drag"))); +} + +/// The width the dock column took in the last frame (tests: an iconic-only dock must take its +/// narrow width and return the rest to the canvas). +#[cfg(test)] +pub(crate) fn dock_panel_width(ctx: &egui::Context) -> f32 { + dock_panel_rect(ctx).width() +} + +/// The actual allocated dock panel rectangle, not its requested pre-render width (tests). +#[cfg(test)] +pub(crate) fn dock_panel_rect(ctx: &egui::Context) -> egui::Rect { + ctx.data(|data| data.get_temp::(egui::Id::unique("photo-dock-panel-rect")).unwrap_or(egui::Rect::NOTHING)) +} + /// The docking layout's protected canvas panel: the document area, with the icon rail on its end /// side, beside the dock, in the Pro themes. pub(crate) fn canvas_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { @@ -30,43 +229,52 @@ pub(crate) fn canvas_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { egui::CentralPanel::default().frame(egui::Frame::NONE.fill(backdrop)).show(ui, |ui| crate::canvas::document_area(app, ui)); } +/// The icon rail's width and its buttons' size, in points. +fn rail_widths(pro: bool) -> (f32, f32) { + if pro { (36.0, 28.0) } else { (44.0, 32.0) } +} + /// Narrow icon rail, unless an embedding app hides it: shows, expands or collapses panel groups. fn rail(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &Tokens) { - let customized = app.ui.docking.is_some(); - let p = app.ui.panels.clone(); - let (rw, rb) = if t.pro { (36.0, 28.0) } else { (44.0, 32.0) }; + let (rw, _) = rail_widths(t.pro); crate::direction::end_panel("rail") .resizable(false) .exact_size(rw) .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(4, 8))) - .show(ui, |ui| { - // The separator is on the canvas side. - let r = ui.max_rect(); - let x = if crate::direction::is_rtl() { r.right() + 6.0 } else { r.left() - 6.0 }; - ui.painter().line_segment([pos2(x, r.top() - 8.0), pos2(x, r.bottom() + 8.0)], Stroke::new(1.0, t.separator)); - ui.spacing_mut().item_spacing.y = 4.0; - use crate::dock::Group; - let entries: [(&str, &str, Group); 6] = [ - ("sliders-horizontal", tl!("Properties"), Group::Properties), - ("navigation", tl!("Navigator"), Group::Navigator), - ("palette", tl!("Color & Swatches"), Group::Color), - ("layers", tl!("Layers"), Group::Layers), - ("clock", tl!("History"), Group::History), - ("brush", tl!("Brushes"), Group::Brushes), - ]; - for (icon, name, g) in entries { - // Studio floats Properties outside the dock. - let docked = t.pro || g != Group::Properties; - let on = if customized { crate::panel_docking::rail_on(app, g) } else { g.shown(&p) && !(docked && app.ui.dock.is_collapsed(g)) }; - if icons::rail_button(ui, icon, rb, on, name).clicked() { - if customized { - crate::panel_docking::rail_click(app, g); - } else { - crate::dock::rail_click(app, g, docked); - } - } + .show(ui, |ui| rail_body(app, ui, t)); +} + +/// The rail's buttons, without the panel that normally holds them. +fn rail_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: &Tokens) { + let customized = app.ui.docking.is_some(); + let p = app.ui.panels.clone(); + let (_, rb) = rail_widths(t.pro); + // The separator is on the canvas side, inside the rail's inset. + let r = ui.max_rect(); + let x = if crate::direction::is_rtl() { r.right() } else { r.left() }; + ui.painter().line_segment([pos2(x, r.top()), pos2(x, r.bottom())], Stroke::new(1.0, t.separator)); + ui.spacing_mut().item_spacing.y = 4.0; + use crate::dock::Group; + let entries: [(&str, &str, Group); 6] = [ + ("sliders-horizontal", tl!("Properties"), Group::Properties), + ("navigation", tl!("Navigator"), Group::Navigator), + ("palette", tl!("Color & Swatches"), Group::Color), + ("layers", tl!("Layers"), Group::Layers), + ("clock", tl!("History"), Group::History), + ("brush", tl!("Brushes"), Group::Brushes), + ]; + for (icon, name, g) in entries { + // Studio floats Properties outside the dock. + let docked = t.pro || g != Group::Properties; + let on = if customized { crate::panel_docking::rail_on(app, g) } else { g.shown(&p) && !(docked && app.ui.dock.is_collapsed(g)) }; + if icons::rail_button(ui, icon, rb, on, name).clicked() { + if customized { + crate::panel_docking::rail_click(app, g); + } else { + crate::dock::rail_click(app, g, docked); } - }); + } + } } /// The dock's narrowest width (points). It is the right dock, on the left in a right-to-left UI. @@ -87,8 +295,10 @@ pub(crate) fn dock_width_id() -> egui::Id { egui::Id::unique("dock-width-request") } -/// Set the right dock's width on the next frame (`ui.set {dockWidth}`); clamped to its range. +/// Set the end dock's width on the next frame (`ui.set {dockWidth}`); clamped to its +/// window-dependent range. An external request supersedes an in-progress outer resize. pub fn request_dock_width(ctx: &egui::Context, w: f32) { + clear_dock_edge_drag(ctx); let range = dock_width_range(ctx.content_rect().width()); let w = if w.is_finite() { w.clamp(*range.start(), *range.end()) } else { *range.start() }; ctx.data_mut(|d| d.insert_temp(dock_width_id(), w)); diff --git a/crates/ui-egui/src/panels/histogram_panel.rs b/crates/ui-egui/src/panels/histogram_panel.rs index 5b10587286..a3576b0df9 100644 --- a/crates/ui-egui/src/panels/histogram_panel.rs +++ b/crates/ui-egui/src/panels/histogram_panel.rs @@ -406,18 +406,19 @@ pub fn update(app: &mut PhotocraftApp, ctx: &egui::Context) { Err(std::sync::mpsc::TryRecvError::Empty) => {} } } - // A revision that changed no pixels (selecting a layer, say) keeps the histogram of the one - // before (#125), and an Uncached Refresh with it. - if let Some(st) = app.session.active() - && tone::view_only(st) - { + // Revisions that changed no pixels since the histogram's (selecting a layer, say) keep it + // (#125), and an Uncached Refresh with it. + if let Some(st) = app.session.active() { let (doc, rev) = (st.doc.id, st.revision); - if app.hist_uncached == Some((doc, rev.wrapping_sub(1))) { + if let Some((d, r)) = app.hist_uncached + && d == doc + && tone::pixels_kept_since(st, r) + { app.hist_uncached = Some((doc, rev)); } if let Some(e) = app.doc_hist.as_mut() && e.key.doc == doc - && e.key.revision.wrapping_add(1) == rev + && tone::pixels_kept_since(st, e.key.revision) { e.key.revision = rev; } diff --git a/crates/ui-egui/src/panels/history.rs b/crates/ui-egui/src/panels/history.rs index 38d3797014..e75dbbb5b9 100644 --- a/crates/ui-egui/src/panels/history.rs +++ b/crates/ui-egui/src/panels/history.rs @@ -62,16 +62,7 @@ pub(super) fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } else if resp.hovered() { ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.5)); } - let icon = match e.as_str() { - s if s.contains("Brush") || s.contains("Eraser") => "brush", - // The Layers panel's controls (layer.setProps). - "Opacity Change" | "Fill Opacity Change" | "Blending Change" => "layers", - s if s.contains("Layer") => "layers", - s if s.contains("Select") || s.contains("Marquee") || s.contains("Deselect") || s.contains("Lasso") => "square-dashed", - s if s.contains("Fill") => "paint-bucket", - "Open" => "image", - _ => "sliders-horizontal", - }; + let icon = step_icon(&e); let color = if is_redo { t.text_faint } else { t.text }; icons::paint( ui, @@ -194,6 +185,24 @@ pub(super) fn history(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } +/// The icon of a History step, from its name. +pub(crate) fn step_icon(step: &str) -> &'static str { + match step { + s if s.contains("Brush") || s.contains("Eraser") => "brush", + // Applying a patch edits pixels; only the Patch tool's lasso is a selection step. + "Patch Selection" => "sliders-horizontal", + // The Layers panel's controls (layer.setProps). + "Opacity Change" | "Fill Opacity Change" | "Blending Change" => "layers", + s if s.contains("Layer") => "layers", + s if s.contains("Select") || s.contains("Marquee") || s.contains("Deselect") || s.contains("Lasso") => "square-dashed", + // The selections the Patch tool draws (select.lasso's historyName). + "Patch Tool" => "square-dashed", + s if s.contains("Fill") => "paint-bucket", + "Open" => "image", + _ => "sliders-horizontal", + } +} + /// The History panel's source column at the left of a state or snapshot row: the History Brush /// icon on the source; a click makes the row the source (`history.setSource`). It sits above the /// row, so the click doesn't also step to the state or snapshot. diff --git a/crates/ui-egui/src/panels/layer_menu_ui/tests.rs b/crates/ui-egui/src/panels/layer_menu_ui/tests.rs index 11c29e58ba..156a7eaaf1 100644 --- a/crates/ui-egui/src/panels/layer_menu_ui/tests.rs +++ b/crates/ui-egui/src/panels/layer_menu_ui/tests.rs @@ -599,3 +599,63 @@ fn every_entry_is_a_known_command() { assert!(crate::menu_catalog::CATALOG.iter().any(|m| m.3 == id) || photocraft_engine::commands::find(id).is_some(), "{id}"); } } + +/// #12324: right-clicking a pixel layer's thumbnail opens Photoshop's thumbnail menu; its Select Pixels +/// loads the clicked layer's transparency, as a ⌘-click on the thumbnail does. The Background's +/// thumbnail, with no transparency to load, keeps the layer menu. +#[test] +fn layer_thumbnail_context_menu_selects_the_clicked_layers_pixels() { + use crate::PhotocraftApp; + use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; + use egui_kittest::{Harness, kittest::Queryable}; + + fn click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, button: PointerButton) { + h.hover_at(at); + h.step(); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: at, button, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(3); + } + + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 100, "height": 60})).unwrap(); + let background = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "Painted"})).unwrap(); + s.execute("select.rect", json!({"x": 60, "y": 0, "width": 40, "height": 60})).unwrap(); + s.execute("edit.fill", json!({"color": "#b04020"})).unwrap(); + let painted = s.active().unwrap().active_layer.unwrap(); + // Another layer is active, and the current selection doesn't overlap the painted pixels. + s.execute("layer.new.layer", json!({"name": "Other active layer"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 60})).unwrap(); + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(s, crate::Services::default()) + }); + let ctx = h.ctx.clone(); + let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"dock": {"collapsed": ["color", "properties", "history", "navigator"]}})); + crate::control::handle(h.state_mut(), &ctx, &req); + h.run_steps(8); + let thumb = |h: &Harness<'_, PhotocraftApp>, layer: photocraft_doc::LayerId| { + crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == layer.0).and_then(|r| r.thumbnail).expect("thumbnail drawn").center() + }; + + let at = thumb(&h, painted); + click(&mut h, at, PointerButton::Secondary); + assert!(h.query_by_label("Blending Options…").is_none(), "the thumbnail menu, not the layer menu"); + for item in ["Small Thumbnails", "Clip Thumbnails to Layer Bounds"] { + h.get_by_label(item); + } + let at = h.get_by_label("Select Pixels").rect().center(); + click(&mut h, at, PointerButton::Primary); + let st = h.state().session.active().unwrap(); + let sel = st.doc.selection.as_ref().expect("a selection"); + assert!(sel.sample_channel(80, 30, 0) > 0.99, "the clicked layer's pixels are selected"); + assert!(sel.sample_channel(10, 30, 0) < 0.01, "the old selection is replaced"); + + let at = thumb(&h, background); + click(&mut h, at, PointerButton::Secondary); + assert!(h.query_by_label("Select Pixels").is_none(), "the Background has no pixels to load"); + h.get_by_label("Blending Options…"); +} diff --git a/crates/ui-egui/src/panels/layer_row.rs b/crates/ui-egui/src/panels/layer_row.rs index e9b984d81f..d0cd501ef8 100644 --- a/crates/ui-egui/src/panels/layer_row.rs +++ b/crates/ui-egui/src/panels/layer_row.rs @@ -568,16 +568,27 @@ fn handle_row_double_click(app: &mut PhotocraftApp, ctx: &egui::Context, rc: &Ro } } -/// The visibility icon has its own color menu, and the layer-mask thumbnail its mask menu (#4575). +/// The visibility icon has its own color menu, the layer-mask thumbnail its mask menu (#4575) +/// and a pixel layer's thumbnail Select Pixels and the thumbnail settings (#12324). fn row_context_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, rc: &RowCtx<'_>, eye_resp: &egui::Response, actions: &mut Vec<(String, Value)>) { let (l, resp, masks, row) = (rc.l, rc.resp, rc.masks, rc.row); let (ctx, selected) = (&ui.ctx().clone(), row.selected); - // The visibility icon has its own color menu, and the layer-mask thumbnail its mask menu - // (#4575); elsewhere use the full layer menu. + // The visibility icon has its own color menu, the layer-mask thumbnail its mask menu + // (#4575) and a pixel layer's thumbnail its thumbnail menu; elsewhere the full layer menu. let on_mask_id = ui.scope_id().with(("mask-menu", l.id.0)); + let on_thumb_id = ui.scope_id().with(("thumb-menu", l.id.0)); if resp.secondary_clicked() { - let on_mask = resp.interact_pointer_pos().and_then(|p| masks.hit(p)) == Some(crate::mask_thumbs_ui::MaskKind::Pixel); - ctx.data_mut(|d| d.insert_temp(on_mask_id, on_mask)); + let pos = resp.interact_pointer_pos(); + let on_mask = pos.and_then(|p| masks.hit(p)) == Some(crate::mask_thumbs_ui::MaskKind::Pixel); + // A pixel layer's thumbnail; not the Background's, which has no transparency to load. + // Type, shape, smart object, fill, adjustment and group thumbnails keep the layer menu + // with their own items (Rasterize, Edit Contents…). + let pixels = matches!(l.content, LayerContent::Raster(_)) && l.frame.is_none() && !rc.doc.is_background(l.id); + let on_thumb = !on_mask && pixels && rc.ts > 0.0 && pos.is_some_and(|p| masks.hit(p).is_none() && rc.thumb.expand(2.0).contains(p)); + ctx.data_mut(|d| { + d.insert_temp(on_mask_id, on_mask); + d.insert_temp(on_thumb_id, on_thumb); + }); } if !eye_resp.secondary_clicked() && !eye_resp.context_menu_opened() { resp.context_menu(|ui| { @@ -586,6 +597,10 @@ fn row_context_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, rc: &RowCtx<'_>, crate::layer_menu_ui::show_mask(app, ui, l, actions); return; } + if ui.ctx().data(|d| d.get_temp::(on_thumb_id)).unwrap_or(false) { + super::layers_empty_menu::show_thumbnail(app, ui, l.id.0, actions); + return; + } // Right-clicking inside a multi-selection keeps it and acts on every selected layer. let on_set = row.multi && selected; if crate::layer_menu_ui::show(app, ui, l, on_set, actions) diff --git a/crates/ui-egui/src/panels/layers_empty_menu.rs b/crates/ui-egui/src/panels/layers_empty_menu.rs index 17c1c0d6e0..69ef46d324 100644 --- a/crates/ui-egui/src/panels/layers_empty_menu.rs +++ b/crates/ui-egui/src/panels/layers_empty_menu.rs @@ -1,5 +1,6 @@ //! The menu a right-click on the empty area below the last layer row opens (#11404): the //! thumbnail size and what a thumbnail frames. Both are the settings Panel Options... edits. +//! A right-click on a layer's thumbnail opens the same menu under Select Pixels (#12324). use serde_json::json; @@ -16,6 +17,17 @@ pub(super) fn sizes() -> [(LayerThumbnailSize, &'static str); 4] { ] } +/// The layer thumbnail's menu: Select Pixels loads the layer's transparency as the selection, +/// as a ⌘-click on the thumbnail does, then the thumbnail settings. +pub(super) fn show_thumbnail(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: u64, actions: &mut Vec<(String, serde_json::Value)>) { + if ui.button(tl!("Select Pixels")).clicked() { + actions.push(("select.loadSelection".into(), json!({"channel": "transparency", "layer": layer, "operation": "new"}))); + ui.close(); + } + ui.separator(); + show(app, ui); +} + pub(super) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let current = app.ui.layers_panel_options.thumbnail_size; for (size, label) in sizes() { diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index df45e61d01..1a0fee434c 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -1,4 +1,6 @@ -use super::brush_controls::{brush_preset_chip, mixer_load_swatch, paint_mode_dropdown, smoothing_field, smoothing_options, tool_mode_dropdown}; +use super::brush_controls::{ + brush_preset_chip, mixer_combination_dropdown, mixer_load_swatch, paint_mode_dropdown, smoothing_field, smoothing_options, tool_mode_dropdown, +}; use super::properties::{select_and_mask_button, selection_mode_buttons}; use super::{BlendMode, Color32, PhotocraftApp, RichText, Sense, Tokens, Tool, Value, icons, json, starts_blend_group, vec2, widgets}; use photocraft_paint::BrushSettings; @@ -179,8 +181,13 @@ fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, } } ui.add_enabled_ui(!block, |ui| { - // A whole number from 1 to 100, as in Photoshop: 0 paints nothing (#11812). - tip(whole_percent_field(ui, tl!("Opacity"), &mut b.opacity, 1.0..=100.0, 62.0), tl!("Set opacity for stroke")); + // A whole number from 1 to 100, as in Photoshop: 0 paints nothing (#11812). The + // Eraser's says so when a typed value was past that (#11938). + if brush { + tip(whole_percent_field(ui, tl!("Opacity"), &mut b.opacity, 1.0..=100.0, 62.0), tl!("Set opacity for stroke")); + } else if eraser_percent(ui, tl!("Opacity"), &mut b.opacity) { + range_alert(&mut app.ui, ONE_TO_100); + } let pressure = pressure_button(ui, b.pressure_opacity, tl!("Always use pressure for opacity"), brush); if tip(pressure, tl!("Always use Pressure for Opacity. When off, Brush Preset controls pressure")).clicked() { b.pressure_opacity = !b.pressure_opacity; @@ -188,14 +195,22 @@ fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, }); // A Pencil- or Block-mode Eraser is always full flow, without build-up (Photoshop). ui.add_enabled_ui(!block && !crate::eraser_ui::pencil_mode(app, app.ui.tool), |ui| { - tip(percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0), tl!("Set flow rate for stroke")); + if brush { + tip(percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0), tl!("Set flow rate for stroke")); + } else if eraser_percent(ui, tl!("Flow"), &mut b.flow) { + range_alert(&mut app.ui, ONE_TO_100); + } let airbrush = icons::button(ui, "sparkles", 24.0, b.build_up, tl!("Enable airbrush-style build-up effects")); if crate::brush_picker::named(airbrush, "Enable airbrush-style build-up effects").clicked() { b.build_up = !b.build_up; } }); opt_label(ui, tl!("Smoothing")); - tip(smoothing_field(ui, b, 58.0), tl!("Set smoothing for stroke\nUse higher values to reduce the shakiness of brush strokes")); + if brush { + tip(smoothing_field(ui, b, 58.0), tl!("Set smoothing for stroke\nUse higher values to reduce the shakiness of brush strokes")); + } else if super::brush_controls::smoothing_field_alerting(ui, b, 58.0).1 { + range_alert(&mut app.ui, ZERO_TO_100); + } smoothing_options(ui, b, brush); widgets::vline(ui, 22.0); let pressure = pressure_button(ui, b.pressure_size, tl!("Always use pressure for size"), brush); @@ -217,10 +232,32 @@ fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, let held = app.held_erase; paint_mode_dropdown(ui, "pencil-mode", b, &mut app.ui.tool_options.pencil_clear, held); whole_percent_field(ui, tl!("Opacity"), &mut b.opacity, 1.0..=100.0, if t.pro { 62.0 } else { 66.0 }); + if t.pro { + // Between Opacity and Smoothing, as measured (#11962). + let pressure = pressure_button(ui, b.pressure_opacity, tl!("Always use pressure for opacity"), true); + if pressure.on_hover_text(tl!("Always use Pressure for Opacity. When off, Brush Preset controls pressure")).clicked() { + b.pressure_opacity = !b.pressure_opacity; + } + } opt_label(ui, tl!("Smoothing")); smoothing_field(ui, b, if t.pro { 58.0 } else { 66.0 }); widgets::vline(ui, 22.0); - widgets::checkbox(ui, &mut app.ui.tool_options.pencil_auto_erase, tl!("Auto Erase")); + widgets::checkbox(ui, &mut app.ui.tool_options.pencil_auto_erase, tl!("Auto Erase")) + .on_hover_text(tl!("Draws background color over foreground colors")); + widgets::vline(ui, 22.0); + if t.pro { + // Between Auto Erase and the Symmetry button the bar adds after this arm (#11962). + let pressure = pressure_button(ui, b.pressure_size, tl!("Always use pressure for size"), true); + if pressure.on_hover_text(tl!("Always use Pressure for Size. When off, Brush Preset controls pressure")).clicked() { + b.pressure_size = !b.pressure_size; + } + } else { + // The other themes show the Brush's labelled switches; the Pencil gets them too. + widgets::toggle(ui, &mut b.pressure_size, tl!("Pressure for Size")) + .on_hover_text(tl!("Always use Pressure for Size. When off, Brush Preset controls pressure")); + widgets::toggle(ui, &mut b.pressure_opacity, tl!("Pressure for Opacity")) + .on_hover_text(tl!("Always use Pressure for Opacity. When off, Brush Preset controls pressure")); + } } Tool::Brush | Tool::Eraser => { brush_preset_chip(ui, b, &mut app.ui); @@ -279,6 +316,9 @@ fn brush_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, *on = !*on; } } + if let Some(r) = mixer_combination_dropdown(ui, &mut app.ui.tool_options.mixer_combination, &mut b.mixer) { + r.on_hover_text(tl!("Useful mixer brush combinations")); + } widgets::vline(ui, 22.0); for (label, value) in [(tl!("Wet"), &mut b.mixer.wet), (tl!("Load"), &mut b.mixer.load), (tl!("Mix"), &mut b.mixer.mix), (tl!("Flow"), &mut b.mixer.flow)] @@ -649,25 +689,13 @@ fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, // Resize Windows to Fit is Preferences › Zoom Resizes Windows itself, as in // Photoshop: one setting, shown in both places (zoom_window_fit.rs). let mut fit = app.session.prefs().general.zoom_resizes_windows; - if widgets::checkbox(ui, &mut fit, tl!("Resize Windows to Fit")).changed() { + if widgets::checkbox(ui, &mut fit, tl!("Resize Windows to Fit")).on_hover_text(tl!("Resize windows when zooming using the Zoom Tool")).changed() { app.session.prefs.edit(|p| p.general.zoom_resizes_windows = fit); } - widgets::checkbox(ui, &mut app.ui.tool_options.zoom_scrubby, tl!("Scrubby Zoom")); - hint( - ui, - &crate::i18n::fmt( - tl!("Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out"), - &[("key", &crate::shortcuts::pretty("Alt"))], - ), - ); - if widgets::secondary_button(ui, tl!("Fit Screen"), 0.0).clicked() - && let Some(i) = app.session.active_index() - { - app.ui.views[i].fit_pending = true; - app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); - app.ui.views[i].zoom_anchor = None; - } - if widgets::secondary_button(ui, "100%", 0.0).clicked() + widgets::checkbox(ui, &mut app.ui.tool_options.zoom_scrubby, tl!("Scrubby Zoom")) + .on_hover_text(tl!("Click and move left or right to scale using the Zoom Tool (OpenGL only)")); + // The same three buttons as the Hand bar, with the reference tooltips (#12068). + if widgets::secondary_button(ui, "100%", 0.0).on_hover_text(tl!("Zoom current window to 1:1")).clicked() && let Some(i) = app.session.active_index() { app.ui.views[i].zoom = 1.0; @@ -676,6 +704,22 @@ fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, app.ui.views[i].fit_pending = false; app.ui.views[i].fill_pending = false; } + if widgets::secondary_button(ui, tl!("Fit Screen"), 0.0).on_hover_text(tl!("Zoom current window to screen size")).clicked() + && let Some(i) = app.session.active_index() + { + app.ui.views[i].fit_pending = true; + app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); + app.ui.views[i].zoom_anchor = None; + app.ui.views[i].fill_pending = false; + } + if widgets::secondary_button(ui, tl!("Fill Screen"), 0.0).on_hover_text(tl!("Zoom current window to fill the screen")).clicked() + && let Some(i) = app.session.active_index() + { + app.ui.views[i].fill_pending = true; + app.ui.views[i].request_zoom_animation(app.session.prefs().general.animated_zoom); + app.ui.views[i].zoom_anchor = None; + app.ui.views[i].fit_pending = false; + } } Tool::RotateView => { hint(ui, tl!("Drag around the center to rotate the view · Shift constrains to 15°")); @@ -695,6 +739,8 @@ fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, } } Tool::Hand => { + widgets::checkbox(ui, &mut app.ui.tool_options.hand_scroll_all, tl!("Scroll All Windows")) + .on_hover_text(tl!("Scroll all open document windows when using the hand tool")); hint(ui, tl!("Drag to pan · hold Space with any tool")); if widgets::secondary_button(ui, "100%", 0.0).clicked() && let Some(i) = app.session.active_index() @@ -727,6 +773,9 @@ fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, } } +#[cfg(test)] +mod zoom_buttons_tests; + /// Width of the Layers panel's Opacity and Fill fields, with room for their pop-up slider's ▾. pub(super) const LAYER_PCT_W: f32 = 66.0 + widgets::POPUP_ARROW_W; @@ -836,6 +885,31 @@ fn pressure_button(ui: &mut egui::Ui, on: bool, name: &str, own_tip: bool) -> eg icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), on, name, !own_tip) } +/// The reference's alerts for an Eraser Opacity or Flow, and Smoothing, typed out of range (#11938). +pub const ONE_TO_100: &str = "An integer between 1% and 100% is required. Closest value inserted."; +pub const ZERO_TO_100: &str = "An integer between 0% and 100% is required. Closest value inserted."; + +/// The Eraser's Opacity or Flow: whole percents 1..100 that say when a typed value was past them. +fn eraser_percent(ui: &mut egui::Ui, label: &str, value: &mut f32) -> bool { + opt_label(ui, label); + let mut percent = *value * 100.0; + let (r, alert) = widgets::value_field_whole_alerting(ui, label, &mut percent, 1.0..=100.0, "%", 62.0); + if r.changed() { + *value = percent / 100.0; + } + alert +} + +/// Shows one of the range alerts as a modal with OK, once even if more than one pass asks. +fn range_alert(ui_state: &mut crate::state::UiState, text: &str) { + let message = tl!(text).to_owned(); + let shown = + ui_state.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message)); + if !shown { + ui_state.open_dialog(crate::state::DialogKind::Error, serde_json::json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } +} + /// [`percent_field`] that keeps whole percents (`33.7` becomes 34 %). A value set elsewhere (a /// `tools.setBrush` fraction, an older saved 0) shows as the whole percent in range. fn whole_percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) -> egui::Response { @@ -852,3 +926,7 @@ fn hint(ui: &mut egui::Ui, s: &str) { let t = Tokens::get(ui.ctx()); ui.label(RichText::new(s).color(t.text_faint)); } + +#[cfg(test)] +#[path = "../eraser_range_alert_tests.rs"] +mod eraser_range_alert_tests; diff --git a/crates/ui-egui/src/panels/options_bar/zoom_buttons_tests.rs b/crates/ui-egui/src/panels/options_bar/zoom_buttons_tests.rs new file mode 100644 index 0000000000..ce00ce0bc7 --- /dev/null +++ b/crates/ui-egui/src/panels/options_bar/zoom_buttons_tests.rs @@ -0,0 +1,69 @@ +//! #12068: the Zoom tool's bar shows 100%, Fit Screen and Fill Screen in that order, with the +//! reference tooltips, and no hint text. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +fn zoom_bar() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 3000, "height": 2000})).unwrap(); + // The bar's fonts are installed after the first frame, so it starts on a tool without "100%". + app.ui.tool = Tool::Move; + let mut h = Harness::builder().with_size(vec2(1600.0, 300.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.state_mut().ui.tool = Tool::Zoom; + h.run_steps(4); + h +} + +#[test] +fn the_buttons_are_100_fit_and_fill_in_that_order() { + let h = zoom_bar(); + let x = |label: &str| h.get_by_label(label).rect().center().x; + assert!(x("Scrubby Zoom") < x("100%"), "after the checkboxes"); + assert!(x("100%") < x("Fit Screen") && x("Fit Screen") < x("Fill Screen")); +} + +#[test] +fn each_control_has_the_reference_tooltip() { + for (label, tip) in [ + ("100%", "Zoom current window to 1:1"), + ("Fit Screen", "Zoom current window to screen size"), + ("Fill Screen", "Zoom current window to fill the screen"), + ("Resize Windows to Fit", "Resize windows when zooming using the Zoom Tool"), + ("Scrubby Zoom", "Click and move left or right to scale using the Zoom Tool (OpenGL only)"), + ] { + let mut h = zoom_bar(); + h.get_by_label(label).hover(); + h.run_steps(60); + assert!(h.query_by_label(tip).is_some(), "{label}: no tooltip {tip:?}"); + } +} + +#[test] +fn the_bar_shows_no_hint_text() { + let h = zoom_bar(); + assert!(h.query_by_label_contains("to zoom out").is_none()); + assert!(h.query_by_label_contains("Click to zoom in").is_none()); +} + +#[test] +fn fill_screen_fills_as_on_the_hand_bar() { + let mut h = zoom_bar(); + h.get_by_label("Fit Screen").click(); + h.run_steps(2); + assert!(h.state().ui.views[0].fit_pending); + h.get_by_label("Fill Screen").click(); + h.run_steps(2); + let v = &h.state().ui.views[0]; + assert!(v.fill_pending && !v.fit_pending); + h.get_by_label("100%").click(); + h.run_steps(2); + let v = &h.state().ui.views[0]; + assert!(!v.fill_pending && !v.fit_pending && v.zoom == 1.0); +} diff --git a/crates/ui-egui/src/panels/panel_docking.rs b/crates/ui-egui/src/panels/panel_docking.rs index 6029ae52b4..6e962cc553 100644 --- a/crates/ui-egui/src/panels/panel_docking.rs +++ b/crates/ui-egui/src/panels/panel_docking.rs @@ -90,6 +90,179 @@ fn default_width(pro: bool) -> f32 { if pro { 290.0 } else { 300.0 } } +/// The end dock of `layout`: follow only the second child of horizontal splits, as craft-ui +/// keeps a side's dock at its window edge; this app builds that dock as `Side::End`. `None` when +/// the layout has no end dock. +fn end_dock_node(node: &Node) -> Option<&Node> { + match node { + Node::Dock { .. } => Some(node), + Node::Split { axis: SplitAxis::Horizontal, second, .. } => end_dock_node(second), + _ => None, + } +} + +/// The end dock's layout facts, computed from one layout snapshot per frame. +pub(crate) struct DockMetrics { + pub(crate) empty: bool, + pub(crate) iconic_only: bool, + pub(crate) width: f32, + pub(crate) minimum: f32, + pub(crate) maximum: f32, +} + +/// The end dock's displayed width, whether it has no panels, and whether every column is iconic. +/// A layout built from the native dock is materialized once here rather than in each helper. +pub(crate) fn dock_metrics(app: &PhotocraftApp) -> DockMetrics { + let layout = match &app.ui.docking { + Some(workspace) => workspace.layout.clone(), + None => legacy(app), + }; + match layout.root.as_ref().and_then(end_dock_node) { + Some(Node::Dock { columns, .. }) if !columns.is_empty() => DockMetrics { + empty: columns.iter().all(|column| column.groups.iter().all(|group| group.panels.is_empty())), + iconic_only: columns.iter().all(|column| column.iconic), + width: columns.iter().map(display_width).sum(), + minimum: columns_minimum(columns), + maximum: columns_maximum(columns), + }, + _ => DockMetrics { empty: true, iconic_only: false, width: default_width(app.ui.theme.is_pro()), minimum: 0.0, maximum: f32::INFINITY }, + } +} + +/// The end dock's displayed width (tests). +#[cfg(test)] +pub(crate) fn dock_width(app: &PhotocraftApp) -> f32 { + dock_metrics(app).width +} + +/// True when the end dock holds no panels at all (tests). +#[cfg(test)] +pub(crate) fn dock_is_empty(app: &PhotocraftApp) -> bool { + dock_metrics(app).empty +} + +/// craft-ui's iconic column width without a saved width, and its renderer's clamp. +pub(crate) const ICONIC_WIDTH: f32 = 36.0; +const ICONIC_MAX_WIDTH: f32 = 240.0; + +/// A column's width as craft-ui draws it: `iconic_width` (default 36, clamped to 36..240) while +/// collapsed to icons, else the expanded width. +fn display_width(column: &Column) -> f32 { + if column.iconic { column.iconic_width.unwrap_or(ICONIC_WIDTH).clamp(ICONIC_WIDTH, ICONIC_MAX_WIDTH) } else { column.width } +} + +/// The canvas panel's least width in points, for the docking layout and the dock-edge layout. +pub(crate) const CANVAS_MIN_WIDTH: f32 = 200.0; + +/// The narrowest column, in points, that still draws a panel's body; a narrower one shows only +/// its chrome. Deliberately independent of [`CANVAS_MIN_WIDTH`], although both are 200. +const PANEL_BODY_MIN_WIDTH: f32 = 200.0; + +/// The least displayed width of a column: the app's 220-point panel minimum, unless the column is +/// iconic (its icons fit in the narrow width) or has no panels. +const MIN_COLUMN_WIDTH: f32 = 220.0; + +/// The least displayed width of `column`: [`ICONIC_WIDTH`] when iconic, one point when it +/// holds no panels, else [`MIN_COLUMN_WIDTH`]. +fn column_minimum(column: &Column) -> f32 { + if column.iconic { + ICONIC_WIDTH + } else if column.groups.iter().all(|group| group.panels.is_empty()) { + 1.0 + } else { + MIN_COLUMN_WIDTH + } +} + +/// The sum of the columns' displayed-width minimums. +fn columns_minimum(columns: &[Column]) -> f32 { + columns.iter().map(column_minimum).sum() +} + +/// The greatest displayed width of a column: iconic columns stop at the renderer's cap, expanded +/// columns can use whatever the window gives them. +fn column_maximum(column: &Column) -> f32 { + if column.iconic { ICONIC_MAX_WIDTH } else { f32::INFINITY } +} + +/// The sum of the columns' displayed-width maximums; infinite while any column is expanded. +fn columns_maximum(columns: &[Column]) -> f32 { + columns.iter().map(column_maximum).sum() +} + +/// Sets a column's displayed width. An iconic column keeps its expanded width for when the user +/// expands it again; only `iconic_width` changes. +fn set_display_width(column: &mut Column, width: f32) { + let width = width.max(1.0); + if column.iconic { + column.iconic_width = Some(width.clamp(ICONIC_WIDTH, ICONIC_MAX_WIDTH)); + } else { + column.width = width; + } +} + +/// Scales every column so their displayed widths add up to `total`, respecting the per-column +/// panel minimum. Returns the resulting displayed total (rounding can differ by a point). +fn scale_columns(columns: &mut [Column], total: f32) -> f32 { + if columns.is_empty() { + return 0.0; + } + // Bring the existing widths into their bounds, then move the total toward the request in + // passes, freezing columns that hit a bound so their refused space reaches the others. + for column in columns.iter_mut() { + let width = display_width(column).clamp(column_minimum(column), column_maximum(column)); + set_display_width(column, width); + } + let minimum = columns_minimum(columns); + let maximum = columns_maximum(columns); + let target = total.clamp(minimum, maximum.max(minimum)).max(1.0); + let mut sum: f32 = columns.iter().map(display_width).sum(); + // Every unfinished pass freezes at least one column; allow a final convergence pass. + for _ in 0..=columns.len() { + let diff = target - sum; + if diff.abs() < 0.5 { + break; + } + let candidates: Vec = columns + .iter() + .enumerate() + .filter( + |(_, column)| { + if diff > 0.0 { display_width(column) < column_maximum(column) - 0.01 } else { display_width(column) > column_minimum(column) + 0.01 } + }, + ) + .map(|(index, _)| index) + .collect(); + if candidates.is_empty() { + break; + } + let share = diff / candidates.len() as f32; + let mut changed = false; + for index in candidates { + let old = display_width(&columns[index]); + let width = (old + share).clamp(column_minimum(&columns[index]), column_maximum(&columns[index])); + if (width - old).abs() > 0.001 { + set_display_width(&mut columns[index], width); + changed = true; + } + } + sum = columns.iter().map(display_width).sum(); + if !changed { + break; + } + } + sum +} + +/// The end dock's columns, following the same horizontal second-child path as [`end_dock_node`]. +fn dock_columns_mut(node: &mut Node) -> Option<&mut Vec>> { + match node { + Node::Dock { columns, .. } => Some(columns), + Node::Split { axis: SplitAxis::Horizontal, second, .. } => dock_columns_mut(second), + _ => None, + } +} + /// The window id of the Studio themes' floating Properties group in a layout built each frame: /// the same every time, with the top bit set, where craft-ui's fresh ids never reach. const PROPERTIES_WINDOW: u64 = (1 << 63) | 0x5052_4f50; @@ -524,9 +697,85 @@ fn app_owned(app: &mut PhotocraftApp, command: DockCommand) -> Result u32 { + ctx.data(|data| data.get_temp::(egui::Id::unique("photo-dock-show-calls")).unwrap_or(0)) +} + +/// The dock column of a canvas-plus-dock layout, with the canvas removed. +fn without_canvas(layout: Layout) -> Layout { + match layout.root { + Some(Node::Split { second, .. }) => Layout { root: Some(*second), floating: layout.floating }, + _ => layout, + } +} + +/// True when the layout's canvas side holds nothing but the canvas. +/// +/// The dock-edge toolbox layout presents the dock column without its canvas so the toolbox can sit +/// between them. That presentation drops the canvas side of the root split, so it is only safe +/// while the canvas is alone there: a panel docked beside the canvas keeps the standard layout, +/// where craft-ui draws it and accepts drops beside it. +pub(crate) fn canvas_alone(app: &PhotocraftApp) -> bool { + match &app.ui.docking { + Some(workspace) => canvas_alone_layout(&workspace.layout), + // The layout built from the native dock always has the canvas alone on its side. + None => true, + } +} + +/// True when the layout is the canvas-beside-dock shape: a horizontal root split whose first +/// child holds only the canvas and whose second child is the dock itself. A trailing split or +/// stack is not an end dock: resizing it would snap back on release, so it keeps the standard +/// layout. +fn canvas_alone_layout(layout: &Layout) -> bool { + match &layout.root { + Some(Node::Split { axis: SplitAxis::Horizontal, first, second, .. }) => { + matches!(first.as_ref(), Node::Tabs { panels, .. } if panels.len() == 1 && panels[0] == CANVAS) && matches!(second.as_ref(), Node::Dock { .. }) + } + _ => false, + } +} + +/// Apply an external width request before the dock-edge panel measures its allocation. +/// Standard rendering consumes the same queue. Without an explicit request, native PanelState +/// migration stays in `show` with its existing canvas-readiness guard. +pub(crate) fn apply_pending_dock_width(app: &mut PhotocraftApp, ctx: &egui::Context) { + let id = crate::panels::dock_width_id(); + let Some(width) = ctx.data(|data| data.get_temp::(id)) else { return }; + // Let `show` restore an invalid workspace before consuming its queued request, as before. + if app.ui.docking.as_ref().is_some_and(|workspace| !valid_workspace(workspace)) { + return; + } + // An explicit request supersedes one-time native migration, including a legacy no-op + // that must not create a custom workspace or wait for the canvas to become ready. + let native_id = crate::panels::panel_state_id(ctx, "dock"); + ctx.data_mut(|data| { + data.remove::(id); + data.remove::(native_id); + }); + let range = crate::panels::dock_width_range(ctx.content_rect().width()); + set_dock_width(app, width.clamp(*range.start(), *range.end())); +} + /// Draw the layout, the canvas included, in the space `ui` has left: the customized workspace, /// else the native dock's arrangement. pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + show_layout(app, ui, false); +} + +/// Draw the workspace layout; `dock_only` drops the canvas so [`show_dock`] draws only the dock +/// column and the toolbox can sit between them. +fn show_layout(app: &mut PhotocraftApp, ui: &mut egui::Ui, dock_only: bool) { let area = area_id(); let changed_workspace = ui.ctx().data_mut(|data| { let previous = data.get_temp::(area.with("generation")); @@ -542,15 +791,13 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let message = "Invalid panel layout; restored the default dock"; app.ui.status = tl!(message).into(); } - if let Some(width) = ui.ctx().data_mut(|data| data.remove_temp::(crate::panels::dock_width_id())) { - let range = crate::panels::dock_width_range(ui.ctx().content_rect().width()); - set_dock_width(app, width.clamp(*range.start(), *range.end())); - } + apply_pending_dock_width(app, ui.ctx()); native_dock_width(app, ui.ctx()); let layout = match &app.ui.docking { Some(workspace) => workspace.layout.clone(), None => legacy(app), }; + let layout = if dock_only { without_canvas(layout) } else { layout }; let collapsed = collapsed_members(app, &layout); let layout = presented(layout, &collapsed); let fillers = fillers(&layout); @@ -587,8 +834,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let strip = style.tab_height; let card: std::collections::HashSet = layout.floating.iter().filter(|window| window.id == PROPERTIES_WINDOW).flat_map(|window| window.panels().cloned()).collect(); - #[cfg(test)] - ui.ctx().data_mut(|data| data.insert_temp(bodies_id(), Vec::<(String, egui::Rect)>::new())); + record::clear_bodies(ui.ctx()); // The panel windows' passes, inside this call, note their keyboard focus again. keyboard_focus(ui.ctx()).lock().unwrap_or_else(|e| e.into_inner()).clear(); let mut output = dock.show_customized( @@ -599,7 +845,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) { permissions, |id| { if id == CANVAS { - craft_ui::docking::PanelLimits { min: egui::vec2(200.0, 120.0), ..Default::default() } + craft_ui::docking::PanelLimits { min: egui::vec2(CANVAS_MIN_WIDTH, 120.0), ..Default::default() } } else if collapsed.contains(id) { craft_ui::docking::PanelLimits { min: egui::vec2(220.0, 0.0), max: egui::vec2(1_000_000.0, 0.0) } } else { @@ -748,25 +994,83 @@ fn pin_group_heights(ctx: &egui::Context, layout: &Layout, actions: &mut actions.splice(0..0, pins); } -/// `ui.set {dockWidth}`: the width of the end dock's outer column. -fn set_dock_width(app: &mut PhotocraftApp, width: f32) { - let Ok(mut workspace) = workspace_of(app) else { return }; - let outer = match workspace.layout.root.as_ref() { - Some(Node::Split { second, .. }) => match second.as_ref() { - Node::Dock { columns, .. } => columns.first().map(|column| (column.width, column.groups.iter().flat_map(|g| g.panels.first()).next().cloned())), - _ => None, - }, - _ => None, - }; - let Some((current, Some(panel))) = outer else { return }; - if current == width { +/// `ui.set {dockWidth}`: the whole end dock width, distributing changes across its columns +/// within their individual minimums and iconic caps. +/// An empty end dock has no column to store the width in; the request is a no-op until the +/// dock gets a column. +pub(crate) fn set_dock_width(app: &mut PhotocraftApp, width: f32) { + if !width.is_finite() || width <= 0.0 { return; } - workspace.locked = false; - if workspace.apply(Action::ResizeColumn { panel, width }, permissions).is_ok() { - workspace.locked = app.session.prefs().workspace_locked; - let returns = app.ui.docking_returns.clone(); - commit(app, workspace, returns); + let Ok(mut workspace) = workspace_of(app) else { return }; + let Some(root) = workspace.layout.root.as_mut() else { return }; + let Some(columns) = dock_columns_mut(root) else { return }; + if columns.is_empty() { + return; + } + // A request for the width the dock already has must stay a no-op: committing the legacy + // layout here would turn a later `ui.set {dockTabs}` into a customized-workspace update. + let current: f32 = columns.iter().map(display_width).sum(); + let compliant = columns.iter().all(|column| (column_minimum(column)..=column_maximum(column)).contains(&display_width(column))); + if compliant && (current - width).abs() < 0.5 { + return; + } + let actual = scale_columns(columns, width); + if actual <= 0.0 { + return; + } + // The columns already carry the requested total; this only brings the split holding the dock + // in step with it. + let mut split_width = actual; + resize_end_dock(root, actual, &mut split_width); + workspace.locked = app.session.prefs().workspace_locked; + let returns = app.ui.docking_returns.clone(); + commit(app, workspace, returns); +} + +/// Set the end dock's total width in place, distributing changes within each column's bounds and +/// keeping its horizontal split in step. Creates the custom workspace from the legacy +/// dock the first time a change is needed. Returns the resulting displayed width, including a +/// legacy no-op, or `None` for rejected input, a locked workspace, or no end-dock column. +pub(crate) fn set_end_dock_total(app: &mut PhotocraftApp, total: f32) -> Option { + if !total.is_finite() || total <= 0.0 || app.session.prefs().workspace_locked { + return None; + } + if app.ui.docking.is_none() { + set_dock_width(app, total); + if app.ui.docking.is_none() { + // A compliant same-width legacy request must not customize the workspace. + let metrics = dock_metrics(app); + return (!metrics.empty).then_some(metrics.width); + } + } + let workspace = app.ui.docking.as_mut()?; + let root = workspace.layout.root.as_mut()?; + let mut actual = total; + if !resize_end_dock(root, total, &mut actual) { + return None; + } + Some(actual) +} + +/// The end dock's columns at `total`, and the split that holds the dock at its window edge. +fn resize_end_dock(node: &mut Node, total: f32, actual: &mut f32) -> bool { + match node { + Node::Dock { columns, .. } => { + if columns.is_empty() { + return false; + } + *actual = scale_columns(columns, total); + true + } + Node::Split { axis: SplitAxis::Horizontal, second, size, .. } => { + let found = resize_end_dock(second, total, actual); + if found && matches!(&**second, Node::Dock { .. }) { + *size = SplitSize::FixedSecond(*actual); + } + found + } + _ => false, } } @@ -850,6 +1154,55 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: &str) { } } +/// What the drawing code notes for the tests to read back; every write is a no-op outside tests. +pub(crate) mod record { + #[cfg(test)] + use super::bodies_id; + + /// Counts a [`super::show_dock`] call, for `show_dock_calls`. + #[cfg(test)] + pub(crate) fn show_dock_call(ctx: &egui::Context) { + ctx.data_mut(|data| { + let id = egui::Id::unique("photo-dock-show-calls"); + data.insert_temp(id, data.get_temp::(id).unwrap_or(0) + 1); + }); + } + + /// Starts this pass's list of drawn panel bodies, for `last_bodies`. + #[cfg(test)] + pub(crate) fn clear_bodies(ctx: &egui::Context) { + ctx.data_mut(|data| data.insert_temp(bodies_id(), Vec::<(String, egui::Rect)>::new())); + } + + /// Notes the body of panel `id`, for `last_bodies`. + #[cfg(test)] + pub(crate) fn body(ctx: &egui::Context, id: &str, rect: egui::Rect) { + ctx.data_mut(|data| data.get_temp_mut_or_default::>(bodies_id()).push((id.to_owned(), rect))); + } + + /// Notes the dock-edge layout's allocated dock rectangle, for `dock_panel_rect`. + #[cfg(test)] + pub(crate) fn dock_panel_rect(ctx: &egui::Context, rect: egui::Rect) { + ctx.data_mut(|data| data.insert_temp(egui::Id::unique("photo-dock-panel-rect"), rect)); + } + + /// Outside tests nothing is noted. + #[cfg(not(test))] + pub(crate) fn show_dock_call(_: &egui::Context) {} + + /// Outside tests nothing is noted. + #[cfg(not(test))] + pub(crate) fn clear_bodies(_: &egui::Context) {} + + /// Outside tests nothing is noted. + #[cfg(not(test))] + pub(crate) fn body(_: &egui::Context, _: &str, _: egui::Rect) {} + + /// Outside tests nothing is noted. + #[cfg(not(test))] + pub(crate) fn dock_panel_rect(_: &egui::Context, _: egui::Rect) {} +} + /// Where tests find panels and docking controls as drawn last frame. #[cfg(test)] pub(crate) mod probe { @@ -1215,9 +1568,10 @@ fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, panel: &str) { } impl craft_ui::docking::DockContent for PanelContent<'_> { + /// Draws panel `id`'s body in `ui`: the canvas, or an expanded panel's contents when the + /// column leaves it at least 200 points. fn body(&mut self, ui: &mut egui::Ui, id: &String) { - #[cfg(test)] - ui.ctx().data_mut(|data| data.get_temp_mut_or_default::>(bodies_id()).push((id.clone(), ui.max_rect()))); + record::body(ui.ctx(), id, ui.max_rect()); if id == CANVAS { crate::panels::canvas_panel(self.app, ui); return; @@ -1228,7 +1582,7 @@ impl craft_ui::docking::DockContent for PanelContent<'_> { } // A window too small for the dock squeezes its column below the panels' minimum width, // which their layouts do not take. - if !self.collapsed.contains(id) && ui.available_width() >= 200.0 { + if !self.collapsed.contains(id) && ui.available_width() >= PANEL_BODY_MIN_WIDTH { let pro = crate::theme::Tokens::get(ui.ctx()).pro; ui.spacing_mut().item_spacing.y = if pro { 0.0 } else { 6.0 }; egui::Frame::NONE.inner_margin(crate::widgets::body_margin(pro)).show(ui, |ui| body(self.app, ui, id)); diff --git a/crates/ui-egui/src/panels/panel_docking/tests.rs b/crates/ui-egui/src/panels/panel_docking/tests.rs index 886e6f0f8a..ef17aa37bd 100644 --- a/crates/ui-egui/src/panels/panel_docking/tests.rs +++ b/crates/ui-egui/src/panels/panel_docking/tests.rs @@ -1,5 +1,5 @@ use super::*; -use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2}; use egui_kittest::{Harness, kittest::Queryable}; fn app() -> PhotocraftApp { @@ -931,3 +931,1436 @@ fn the_native_dock_width_sizes_the_default_column() { assert_eq!(columns[0].width, 380.0); assert!(h.ctx.data_mut(|data| data.get_persisted::(key)).is_none(), "taken once"); } + +/// The dock-edge layout is only chosen for a horizontal root split whose canvas side is the lone +/// canvas and whose other side is the end dock itself. +#[test] +fn the_dock_edge_layout_only_applies_with_the_canvas_alone() { + let tabs = |panel: &str| Node::Tabs { panels: vec![panel.to_owned()], active: 0 }; + let dock = |panels: Vec<&str>, width: f32| Node::Dock { + side: Side::End, + columns: vec![Column::new(vec![craft_ui::docking::Group::new(panels.into_iter().map(str::to_owned).collect(), 0)], width)], + }; + let aside = |first: Node| Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedSecond(280.0), + first: Box::new(first), + second: Box::new(dock(vec!["color"], 280.0)), + }; + + let alone = Layout { root: Some(aside(tabs(CANVAS))), floating: Vec::new() }; + assert!(canvas_alone_layout(&alone), "{alone:?}"); + + // A panel docked beside the canvas splits the canvas side: not alone any more. + let beside = + Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedFirst(400.0), first: Box::new(tabs("layers")), second: Box::new(tabs(CANVAS)) }; + let layout = Layout { root: Some(aside(beside)), floating: Vec::new() }; + assert!(!canvas_alone_layout(&layout), "{layout:?}"); + + // The second child must be the end dock itself: a trailing split or tabs cannot be resized, + // so the handle would snap back on release. + let not_a_dock = Layout { + root: Some(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedSecond(280.0), + first: Box::new(tabs(CANVAS)), + second: Box::new(tabs("color")), + }), + floating: Vec::new(), + }; + assert!(!canvas_alone_layout(¬_a_dock), "{not_a_dock:?}"); + + // A vertical root split with the canvas above another panel is not the canvas-beside-dock shape. + let vertical = Layout { + root: Some(Node::Split { + axis: SplitAxis::Vertical, + size: SplitSize::FixedSecond(280.0), + first: Box::new(tabs(CANVAS)), + second: Box::new(dock(vec!["color"], 280.0)), + }), + floating: Vec::new(), + }; + assert!(!canvas_alone_layout(&vertical), "{vertical:?}"); +} + +/// The end dock is followed through horizontal splits only; a vertical or tabs sibling is not an +/// end dock, so resizing it returns false instead of half-applying. +#[test] +fn the_end_dock_is_only_the_horizontal_split_s_second_child() { + let tabs = |panel: &str| Node::Tabs { panels: vec![panel.to_owned()], active: 0 }; + let dock = Node::Dock { side: Side::End, columns: vec![Column::new(vec![craft_ui::docking::Group::new(vec!["color".to_owned()], 0)], 260.0)] }; + let mut vertical = + Node::Split { axis: SplitAxis::Vertical, size: SplitSize::FixedSecond(300.0), first: Box::new(tabs(CANVAS)), second: Box::new(dock.clone()) }; + assert!(end_dock_node(&vertical).is_none(), "a vertical split has no end dock"); + let mut actual = 0.0; + assert!(!resize_end_dock(&mut vertical, 320.0, &mut actual), "resizing a vertical dock must not follow the split"); + + let mut horizontal = + Node::Split { axis: SplitAxis::Horizontal, size: SplitSize::FixedSecond(300.0), first: Box::new(tabs(CANVAS)), second: Box::new(dock) }; + assert!(end_dock_node(&horizontal).is_some()); + let mut actual = 0.0; + assert!(resize_end_dock(&mut horizontal, 320.0, &mut actual)); + assert!((actual - 320.0).abs() < 0.5, "the end dock takes the requested width, got {actual}"); +} + +/// The dock-only mode is an argument of one call, so a dock-only frame never leaves a later +/// standard layout without its canvas. +#[test] +fn dock_only_frames_never_leak_into_the_standard_layout() { + let mut ready = false; + let dock_only = std::rc::Rc::new(std::cell::Cell::new(false)); + let mode = dock_only.clone(); + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + ready = true; + return; + } + if mode.get() { show_dock(app, ui) } else { show(app, ui) } + }, + app(), + ); + let canvas_drawn = |h: &Harness<'static, PhotocraftApp>| last_bodies(&h.ctx).iter().any(|(id, _)| id == CANVAS); + h.run_steps(2); + for _ in 0..3 { + dock_only.set(true); + h.step(); + assert!(!canvas_drawn(&h), "show_dock draws no canvas"); + dock_only.set(false); + h.step(); + assert!(canvas_drawn(&h), "the standard layout after a dock-only frame keeps its canvas"); + } +} + +/// `ui.set` still refuses an unknown toolbar side, though saved panels read one as `Start`. +#[test] +fn ui_set_refuses_an_unknown_toolbar_side() { + let mut app = app(); + let ctx = egui::Context::default(); + for bad in [json!("diagonal"), json!(5), json!(null)] { + let reply = control_set(&mut app, &ctx, json!({"panels": {"toolbar_side": bad, "layers": false}})); + assert_ne!(reply["ok"], true, "{bad}: {reply}"); + assert_eq!(app.ui.panels.toolbar_side, crate::state::ToolbarSide::Start); + assert!(app.ui.panels.layers, "{bad}: a refused request changes nothing"); + } + let reply = control_set(&mut app, &ctx, json!({"panels": {"toolbar_side": "right"}})); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(app.ui.panels.toolbar_side, crate::state::ToolbarSide::Right); +} + +/// The toolbar lands on the requested physical side in every interface theme. +#[test] +fn the_toolbar_side_toggle_works_in_every_interface_theme() { + use crate::state::ToolbarSide; + + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + ready = true; + return; + } + crate::panels::toolbar(app, ui); + }, + app(), + ); + for kind in crate::theme::ThemeKind::ALL { + crate::theme::apply(&h.ctx, kind); + h.state_mut().ui.panels.toolbar_side = ToolbarSide::Left; + h.run_steps(2); + // The header's chevron carries the toolbar's label; its screen X is the panel's side. + let left = h.get_by_label("Toolbar").rect().center().x; + assert!(left < 640.0, "{kind:?}: left toolbar at {left}"); + + // The dock button itself moves the toolbar, rather than the test setting the state. + h.get_by_label("Move Toolbar to the Right").click(); + h.run_steps(2); + assert_eq!(h.state().ui.panels.toolbar_side, ToolbarSide::Right, "{kind:?}: the button moves the toolbar right"); + let right = h.get_by_label("Toolbar").rect().center().x; + assert!(right > 640.0, "{kind:?}: right toolbar at {right}"); + // A grouped tool's flyout opens towards the canvas, to the left of its button. + h.query_by_label_contains("Rectangular Marquee Tool").expect("the marquee slot").click_secondary(); + h.run_steps(2); + let (key, button) = h.ctx.data(|d| d.get_temp::<(egui::Id, egui::Rect)>(egui::Id::unique("tool-flyout"))).expect("the flyout is open"); + let flyout = h.ctx.memory(|m| m.area_rect(key.with("flyout"))).expect("the flyout is drawn"); + assert!(flyout.right() <= button.left(), "{kind:?}: flyout {flyout:?} left of its button {button:?}"); + h.query_by_label_contains("Rectangular Marquee Tool").expect("the marquee slot").click_secondary(); + h.run_steps(2); + + h.get_by_label("Move Toolbar to the Left").click(); + h.run_steps(2); + assert_eq!(h.state().ui.panels.toolbar_side, ToolbarSide::Left, "{kind:?}: the button moves the toolbar left"); + let back = h.get_by_label("Toolbar").rect().center().x; + assert!(back < 640.0, "{kind:?}: left toolbar again at {back}"); + } +} + +/// Moving the toolbar persists at click time, even when the dock is not drawn. +#[test] +fn moving_the_toolbar_persists_without_the_dock() { + use crate::state::ToolbarSide; + let mut app = app(); + app.session.prefs.edit(|p| p.workspace.remember_workspace_changes = true); + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + ready = true; + return; + } + crate::panels::toolbar(app, ui); + }, + app, + ); + h.run_steps(2); + h.get_by_label("Move Toolbar to the Right").click(); + h.run_steps(1); + assert_eq!(h.state().ui.panels.toolbar_side, ToolbarSide::Right); + let saved = &h.state().session.prefs().panel_layout; + assert_eq!(saved["panels"]["toolbar_side"], "right", "the toolbar side is persisted without the dock: {saved}"); +} + +/// A dock-edge harness: draw only the dock column, as the dock-edge frame layout does. +fn dock_panel_harness(app: PhotocraftApp, size: egui::Vec2, theme: crate::theme::ThemeKind) -> Harness<'static, PhotocraftApp> { + let mut ready = false; + let mut harness = Harness::builder().with_size(size).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + PhotocraftApp::setup_context(ui.ctx(), theme); + ready = true; + return; + } + crate::panels::dock_panel(app, ui); + }, + app, + ); + harness.run_steps(4); + harness +} + +/// [`dock_panel_harness`] in the Pro Medium theme. +fn dock_edge_harness(app: PhotocraftApp, size: egui::Vec2) -> Harness<'static, PhotocraftApp> { + dock_panel_harness(app, size, crate::theme::ThemeKind::ProMedium) +} + +/// The dock-edge handle resizes the dock and keeps the new width after release; a locked +/// workspace makes the same drag a no-op. +#[test] +fn the_dock_edge_handle_resizes_and_a_locked_workspace_refuses_it() { + let drag_once = |locked: bool| -> (f32, f32, f32) { + let mut app = app(); + app.run("window.panel.move", json!({"panel":"swatches","anchor":"layers"})).unwrap(); + if locked { + app.session.prefs.edit(|p| p.workspace_locked = true); + } + let mut h = dock_edge_harness(app, vec2(1280.0, 800.0)); + let stored = dock_width(h.state()); + let rail = if h.state().ui.panels.rail { if h.state().ui.theme.is_pro() { 36.0 } else { 44.0 } } else { 0.0 }; + let edge = 1280.0 - (stored + rail); + drag(&mut h, pos2(edge, 400.0), pos2(edge + 60.0, 400.0)); + let resized = dock_width(h.state()); + h.run_steps(4); + let settled = dock_width(h.state()); + (stored, resized, settled) + }; + + let (_, resized, settled) = drag_once(false); + assert!(resized < 290.0, "dragging right should shrink the dock, got {resized}"); + assert!((settled - resized).abs() < 1.0, "the resized width must not snap back: {resized} then {settled}"); + + let (locked_stored, locked_resized, locked_settled) = drag_once(true); + assert!((locked_resized - locked_settled).abs() < 1.0); + assert!((locked_resized - locked_stored).abs() < 1.0, "a locked workspace keeps its pre-drag width: {locked_stored} then {locked_resized}"); +} + +/// Asking for the width the dock already has is a no-op and must not create a customized +/// workspace: a later `ui.set {dockTabs}` then keeps its legacy collapse handling. +#[test] +fn setting_the_current_dock_width_keeps_the_legacy_layout() { + let mut app = app(); + let current = dock_width(&app); + assert!(app.ui.docking.is_none(), "the app starts on the native dock"); + set_dock_width(&mut app, current); + assert!(app.ui.docking.is_none(), "a same-width request must not create a workspace"); + + // The next legacy operation must still take the legacy path: selecting a tab in a collapsed + // group selects it without expanding the group or customizing the workspace. + app.ui.dock.set_collapsed(crate::dock::Group::Properties, true); + let ctx = egui::Context::default(); + let (req, _rx) = crate::control::ControlRequest::new("ui.set", json!({"dockTabs": {"properties": 1}})); + crate::control::handle(&mut app, &ctx, &req); + assert_eq!(app.ui.dock_tabs.properties, 1, "the requested tab is selected"); + assert!(app.ui.dock.is_collapsed(crate::dock::Group::Properties), "the collapsed group stays collapsed"); + assert!(app.ui.docking.is_none(), "tab selection still did not customize the workspace"); +} + +/// Screen picking disables the parent UI mid-drag, so the handle never sees the release. The +/// stored drag must be dropped, saves must resume, and a later pointer must not apply the old +/// start. +#[test] +fn disabling_the_ui_cancels_a_dock_edge_drag() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + + let mut app = app(); + app.run("window.panel.move", json!({"panel":"swatches","anchor":"layers"})).unwrap(); + app.session.prefs.edit(|p| p.workspace.remember_workspace_changes = true); + let disabled = Arc::new(AtomicBool::new(false)); + let flag = disabled.clone(); + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + ready = true; + return; + } + if flag.load(Ordering::Relaxed) { + ui.disable(); + } + crate::panels::dock_panel(app, ui); + }, + app, + ); + h.run_steps(4); + let stored = dock_width(h.state()); + let before = h.state().session.prefs().panel_layout.clone(); + let rail = if h.state().ui.panels.rail { if h.state().ui.theme.is_pro() { 36.0 } else { 44.0 } } else { 0.0 }; + let edge = 1280.0 - (stored + rail); + h.event(Event::PointerMoved(pos2(edge, 400.0))); + h.run_steps(1); + h.event(Event::PointerButton { pos: pos2(edge, 400.0), button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerMoved(pos2(edge + 40.0, 400.0))); + h.run_steps(2); + assert!(crate::panels::dock_edge_drag_active(&h.ctx), "the resize drag started"); + assert_eq!(h.state().session.prefs().panel_layout, before, "a held drag is not saved"); + + disabled.store(true, Ordering::Relaxed); + h.run_steps(1); + assert!(!crate::panels::dock_edge_drag_active(&h.ctx), "disabling cancels the held drag before any release"); + h.event(Event::PointerButton { pos: pos2(edge + 40.0, 400.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert!(!crate::panels::dock_edge_drag_active(&h.ctx), "a disabled UI clears the stored drag"); + // Saves resume once the drag is dropped, even while the UI stays disabled: the width the + // held drag reached, which was not saved while held, is saved now. + let saved = &h.state().session.prefs().panel_layout; + assert_ne!(*saved, before, "the cancelled drag's width is saved"); + assert_eq!(*saved, crate::dock::snapshot(h.state()), "the saved layout is the live one after the cancel"); + let settled = dock_width(h.state()); + + disabled.store(false, Ordering::Relaxed); + h.run_steps(3); + h.event(Event::PointerMoved(pos2(edge - 120.0, 400.0))); + h.run_steps(2); + assert!((dock_width(h.state()) - settled).abs() < 0.5, "a stale drag start must not resize the dock after re-enable"); + // Saves resume: a width change made after re-enabling reaches the saved layout. + let resumed = h.state().session.prefs().panel_layout.clone(); + let ctx = h.ctx.clone(); + assert_eq!(control_set(h.state_mut(), &ctx, json!({"dockWidth": settled + 60.0}))["ok"], true); + h.run_steps(3); + assert!((dock_width(h.state()) - settled - 60.0).abs() < 0.5, "the new width is applied, got {}", dock_width(h.state())); + let saved = &h.state().session.prefs().panel_layout; + assert_ne!(*saved, resumed, "the width change after re-enable is saved"); + assert_eq!(*saved, crate::dock::snapshot(h.state()), "the saved layout is the new live one"); +} + +/// `ui.set {dockWidth}` sets the whole end dock, scaling every column rather than only the outer +/// one; the split holding the dock follows the new total. +#[test] +fn ui_set_dock_width_scales_every_column() { + let mut app = app(); + let mut layout = legacy(&app); + let used: std::collections::HashSet = layout.panels().into_iter().map(|panel| panel.to_string()).collect(); + let extra = PANELS.iter().map(|(id, _, _)| *id).find(|id| !used.contains(*id)).expect("a free panel id"); + { + let root = layout.root.as_mut().expect("the legacy layout has a root"); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns.push(Column::new(vec![craft_ui::docking::Group::new(vec![extra.to_owned()], 0)], 180.0)); + } + app.ui.docking = Some(Workspace::new(layout)); + // The extra 180-point column first comes up to its 220-point minimum; the rest of the change + // is shared equally between the two columns. + let share = (520.0 - end_columns(&app)[0].width - 220.0) / 2.0; + let split = [end_columns(&app)[0].width + share, 220.0 + share]; + let total = |app: &PhotocraftApp| -> f32 { + let root = app.ui.docking.as_ref().expect("a customized workspace").layout.root.as_ref().expect("root"); + let dock = match root { + Node::Split { second, .. } => second.as_ref(), + _ => root, + }; + match dock { + Node::Dock { columns, .. } => columns.iter().map(|column| column.width).sum(), + _ => 0.0, + } + }; + let before = total(&app); + set_dock_width(&mut app, 520.0); + let after = total(&app); + assert!((after - 520.0).abs() < 1.0, "the whole dock should be 520 points, got {after} (was {before})"); + let widths: Vec = { + let root = app.ui.docking.as_ref().unwrap().layout.root.as_ref().unwrap(); + let dock = match root { + Node::Split { second, .. } => second.as_ref(), + _ => root, + }; + match dock { + Node::Dock { columns, .. } => columns.iter().map(|column| column.width).collect(), + _ => Vec::new(), + } + }; + assert_eq!(widths.len(), 2, "both columns are kept"); + assert!(widths.iter().all(|width| *width > 0.0), "every column keeps a positive width: {widths:?}"); + assert!(widths.iter().zip(split).all(|(width, expected)| (width - expected).abs() < 1.0), "both columns share the change: {widths:?}, expected {split:?}"); + + // A target below the sum of the columns' 220-point panel minima must stop at that minimum, + // not starve a column while leaving the other untouched. + set_dock_width(&mut app, 250.0); + let after = total(&app); + assert!((after - 440.0).abs() < 1.0, "two columns keep the 440-point minimum, got {after}"); + let widths: Vec = { + let root = app.ui.docking.as_ref().unwrap().layout.root.as_ref().unwrap(); + let dock = match root { + Node::Split { second, .. } => second.as_ref(), + _ => root, + }; + match dock { + Node::Dock { columns, .. } => columns.iter().map(|column| column.width).collect(), + _ => Vec::new(), + } + }; + assert!(widths.iter().all(|width| *width >= 219.5), "every column keeps the panel minimum: {widths:?}"); + assert!(widths.iter().all(|width| *width < 221.0), "the minimum is shared between the columns: {widths:?}"); +} + +/// `ui.set {dockWidth}` travels through the queued request and the rendered dock pass, scaling a +/// multi-column dock to the requested total. +#[test] +fn ui_set_dock_width_queues_and_scales_every_column_when_drawn() { + let mut app = app(); + let mut layout = legacy(&app); + let used: std::collections::HashSet = layout.panels().into_iter().map(|panel| panel.to_string()).collect(); + let extra = PANELS.iter().map(|(id, _, _)| *id).find(|id| !used.contains(*id)).expect("a free panel id"); + { + let root = layout.root.as_mut().expect("the legacy layout has a root"); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns.push(Column::new(vec![craft_ui::docking::Group::new(vec![extra.to_owned()], 0)], 180.0)); + } + app.ui.docking = Some(Workspace::new(layout)); + let mut h = dock_panel_harness(app, vec2(1280.0, 800.0), crate::theme::ThemeKind::ProMedium); + // As in `ui_set_dock_width_scales_every_column`: the extra column comes up to its 220-point + // minimum and the rest of the change is shared equally. + let share = (520.0 - end_columns(h.state())[0].width - 220.0) / 2.0; + let split = [end_columns(h.state())[0].width + share, 220.0 + share]; + crate::panels::request_dock_width(&h.ctx, 520.0); + h.run_steps(2); + let root = h.state().ui.docking.as_ref().expect("a workspace").layout.root.as_ref().expect("root"); + let dock = match root { + Node::Split { second, .. } => second.as_ref(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + let widths: Vec = columns.iter().map(|column| column.width).collect(); + assert_eq!(widths.len(), 2, "both columns are kept"); + assert!(widths.iter().all(|width| *width > 0.0), "every column keeps a positive width: {widths:?}"); + let total: f32 = widths.iter().sum(); + assert!((total - 520.0).abs() < 1.0, "the queued request sets the whole dock to 520 points, got {total} from {widths:?}"); + assert!(widths.iter().zip(split).all(|(width, expected)| (width - expected).abs() < 1.0), "both columns share the change: {widths:?}, expected {split:?}"); +} + +/// A narrow window must still give the canvas its 200-point minimum; the dock shrinks instead. +#[test] +fn a_narrow_window_keeps_the_canvas_minimum() { + let mut app = app(); + let mut layout = legacy(&app); + { + let root = layout.root.as_mut().expect("the legacy layout has a root"); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns[0].width = 520.0; + } + app.ui.docking = Some(Workspace::new(layout)); + app.ui.panels.rail = true; + let h = dock_panel_harness(app, vec2(700.0, 600.0), crate::theme::ThemeKind::ProMedium); + let panel = crate::panels::dock_panel_width(&h.ctx); + let toolbar = crate::panels::toolbar::toolbar_width(h.state().ui.theme.is_pro(), h.state().ui.panels.toolbar_double); + let canvas = 700.0 - panel - toolbar; + assert!(canvas >= 199.0, "the canvas keeps its 200-point minimum, got {canvas} (dock {panel}, toolbar {toolbar})"); +} + +/// The empty dock still renders its docking pass but must not consume the parent layout, so the +/// toolbar and canvas keep their space. +#[test] +fn an_empty_dock_keeps_the_parent_layout_for_toolbar_and_canvas() { + let mut app = app(); + let layout = Layout { + root: Some(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedSecond(0.0), + first: Box::new(Node::Tabs { panels: vec![CANVAS.to_owned()], active: 0 }), + second: Box::new(Node::Dock { side: Side::End, columns: Vec::new() }), + }), + floating: Vec::new(), + }; + app.ui.docking = Some(Workspace::new(layout)); + app.ui.panels.rail = false; + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + ready = true; + return; + } + crate::panels::dock_panel(app, ui); + let remaining = ui.available_width(); + ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("empty-dock-remaining"), remaining)); + crate::panels::toolbar(app, ui); + egui::CentralPanel::default().show(ui, |_| {}); + }, + app, + ); + h.run_steps(4); + let remaining = h.ctx.data(|data| data.get_temp::(egui::Id::unique("empty-dock-remaining")).unwrap_or(0.0)); + assert!(remaining > 1200.0, "the empty dock must not consume the parent layout, left {remaining}"); + assert!(h.get_by_label("Toolbar").rect().is_positive(), "the toolbar still draws"); +} + +/// An empty dock must still run the docking pass, because Studio draws its floating Properties +/// group from it, and the zero-width dock must not lose it with or without the rail. +#[test] +fn an_empty_dock_still_draws_studio_floating_properties() { + for rail in [true, false] { + let mut app = app(); + let layout = Layout { + root: Some(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedSecond(0.0), + first: Box::new(Node::Tabs { panels: vec![CANVAS.to_owned()], active: 0 }), + second: Box::new(Node::Dock { side: Side::End, columns: Vec::new() }), + }), + floating: vec![Floating::single(vec!["properties".to_owned()], 0, [120.0, 160.0, 320.0, 440.0])], + }; + app.ui.docking = Some(Workspace::new(layout)); + app.ui.panels.rail = rail; + let h = dock_panel_harness(app, vec2(1280.0, 800.0), crate::theme::ThemeKind::Studio); + assert!(dock_is_empty(h.state()), "rail={rail}: the dock is empty"); + assert!(show_dock_calls(&h.ctx) > 0, "rail={rail}: the docking pass must still run for floating windows"); + let rect = floating_rect(&h, "properties"); + assert!(rect.is_positive(), "rail={rail}: floating Properties must be drawn, got {rect:?}"); + } +} + +/// A column collapsed to icons reserves its `iconic_width`, not the expanded width; resizing the +/// edge keeps that iconic width in step. +#[test] +fn an_iconic_dock_column_takes_its_iconic_width() { + let mut app = app(); + let mut layout = legacy(&app); + { + let root = layout.root.as_mut().expect("the legacy layout has a root"); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns[0].iconic = true; + columns[0].iconic_width = Some(36.0); + } + let expanded = { + let root = layout.root.as_ref().expect("the legacy layout has a root"); + let dock = match root { + Node::Split { second, .. } => second.as_ref(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns[0].width + }; + app.ui.docking = Some(Workspace::new(layout)); + assert!((dock_width(&app) - 36.0).abs() < 0.5, "the iconic column displays 36 points, got {}", dock_width(&app)); + assert!(set_end_dock_total(&mut app, 220.0).is_some(), "the dock-edge resize accepts an iconic dock"); + assert!((dock_width(&app) - 220.0).abs() < 1.0, "after the resize the dock displays 220 points, got {}", dock_width(&app)); + let root = app.ui.docking.as_ref().unwrap().layout.root.as_ref().unwrap(); + let dock = match root { + Node::Split { second, .. } => second.as_ref(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + assert!(columns[0].iconic_width.unwrap_or(0.0) > 200.0, "iconic_width follows the resize: {:?}", columns[0].iconic_width); + assert!((columns[0].width - expanded).abs() < 0.5, "resizing while iconic keeps the expanded width: {} vs {expanded}", columns[0].width); + + let root = app.ui.docking.as_mut().unwrap().layout.root.as_mut().unwrap(); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns[0].iconic = false; + assert!((dock_width(&app) - expanded).abs() < 0.5, "expanding restores the expanded width, got {} (was {expanded})", dock_width(&app)); +} + +/// Collapsing a column through craft-ui's action leaves `iconic_width` unset; the dock must use +/// the renderer's 36-point default rather than the expanded width. +#[test] +fn an_iconic_only_dock_keeps_its_narrow_panel() { + let mut app = app(); + let layout = legacy(&app); + let panel = { + let root = layout.root.as_ref().expect("the legacy layout has a root"); + let dock = match root { + Node::Split { second, .. } => second.as_ref(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns[0].groups[0].panels[0].clone() + }; + let mut workspace = Workspace::new(layout); + workspace.apply(Action::SetIconic { panel, iconic: true }, permissions).expect("the column collapses"); + { + let root = workspace.layout.root.as_ref().expect("root"); + let dock = match root { + Node::Split { second, .. } => second.as_ref(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + assert!(columns[0].iconic); + assert!(columns[0].iconic_width.is_none(), "the collapse action leaves the stored width unset"); + } + app.ui.docking = Some(workspace); + assert!((dock_width(&app) - 36.0).abs() < 0.5, "an unset iconic width displays 36 points, got {}", dock_width(&app)); + let h = dock_panel_harness(app, vec2(1280.0, 800.0), crate::theme::ThemeKind::ProMedium); + let rail = if h.state().ui.panels.rail { 36.0 } else { 0.0 }; + let drawn = crate::panels::dock_panel_width(&h.ctx); + assert!((drawn - (36.0 + rail)).abs() < 2.0, "the iconic panel is its 36 points plus the rail ({rail}), got {drawn}"); + assert!(drawn < 120.0, "the iconic panel must not take the expanded minimum, got {drawn}"); +} + +/// Stored iconic widths are clamped to the renderer's 36..240 bounds. +#[test] +fn iconic_widths_follow_the_renderer_clamp() { + let mut app = app(); + let mut layout = legacy(&app); + { + let root = layout.root.as_mut().expect("the legacy layout has a root"); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns[0].iconic = true; + columns[0].iconic_width = Some(500.0); + } + app.ui.docking = Some(Workspace::new(layout)); + assert!((dock_width(&app) - 240.0).abs() < 0.5, "a stored 500 displays at most 240, got {}", dock_width(&app)); + let root = app.ui.docking.as_mut().unwrap().layout.root.as_mut().unwrap(); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns[0].iconic_width = Some(10.0); + assert!((dock_width(&app) - 36.0).abs() < 0.5, "a stored 10 displays at least 36, got {}", dock_width(&app)); + let root = app.ui.docking.as_mut().unwrap().layout.root.as_mut().unwrap(); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns[0].iconic_width = None; + assert!((dock_width(&app) - ICONIC_WIDTH).abs() < 0.5, "no saved width displays craft-ui's default 36, got {}", dock_width(&app)); + let style = craft_ui::docking::DockStyle::default(); + assert_eq!((style.iconic_width, style.iconic_max_width), (ICONIC_WIDTH, ICONIC_MAX_WIDTH), "the renderer's defaults"); +} +/// Closing every panel leaves the dock with nothing in it, which the dock-edge layout uses to +/// take no width for the column. +#[test] +fn an_empty_dock_has_no_panels() { + let mut app = app(); + assert!(!dock_is_empty(&app), "the default dock shows its panels"); + app.run("window.panel.move", json!({"panel":"swatches","anchor":"layers"})).unwrap(); + { + let root = app.ui.docking.as_mut().expect("a customized workspace").layout.root.as_mut().expect("root"); + let Node::Split { second, .. } = root else { panic!("the canvas is beside the dock") }; + **second = Node::Dock { side: Side::End, columns: Vec::new() }; + } + assert!(dock_is_empty(&app), "a dock with no columns has nothing to show"); +} + +/// Width refused by the iconic 240-point cap reaches a column that can still grow. +#[test] +fn iconic_cap_surplus_goes_to_expandable_columns() { + let mut app = app(); + let mut layout = legacy(&app); + let used: std::collections::HashSet = layout.panels().into_iter().map(|panel| panel.to_string()).collect(); + let extra = PANELS.iter().map(|(id, _, _)| *id).find(|id| !used.contains(*id)).expect("a free panel id"); + { + let root = layout.root.as_mut().expect("the legacy layout has a root"); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns[0].iconic = true; + columns[0].iconic_width = Some(240.0); + columns.push(Column::new(vec![craft_ui::docking::Group::new(vec![extra.to_owned()], 0)], 220.0)); + } + app.ui.docking = Some(Workspace::new(layout)); + set_dock_width(&mut app, 600.0); + let root = app.ui.docking.as_ref().expect("a workspace").layout.root.as_ref().expect("root"); + let dock = match root { + Node::Split { second, .. } => second.as_ref(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + let displayed: Vec = + columns.iter().map(|column| if column.iconic { column.iconic_width.unwrap_or(36.0).clamp(36.0, 240.0) } else { column.width }).collect(); + let total: f32 = displayed.iter().sum(); + assert!((total - 600.0).abs() < 1.0, "the requested total is reached: {displayed:?}"); + assert!((displayed[0] - 240.0).abs() < 0.5, "the iconic column stays at its cap: {displayed:?}"); + assert!((displayed[1] - 360.0).abs() < 1.0, "the expandable column takes the surplus: {displayed:?}"); +} + +/// The rendered panel uses the width the model actually stored when a drag asks for less than the +/// column minimum, during the drag and after release. +#[test] +fn dock_panel_draws_the_actual_minimum_during_and_after_a_drag() { + let mut app = app(); + let mut layout = legacy(&app); + let used: std::collections::HashSet = layout.panels().into_iter().map(|panel| panel.to_string()).collect(); + let extra = PANELS.iter().map(|(id, _, _)| *id).find(|id| !used.contains(*id)).expect("a free panel id"); + { + let root = layout.root.as_mut().expect("the legacy layout has a root"); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns.push(Column::new(vec![craft_ui::docking::Group::new(vec![extra.to_owned()], 0)], 180.0)); + } + app.ui.docking = Some(Workspace::new(layout)); + let mut h = dock_edge_harness(app, vec2(1280.0, 800.0)); + let rail = if h.state().ui.panels.rail { 36.0 } else { 0.0 }; + let start = begin_outer_resize(&mut h); + let edge = start.x; + h.event(Event::PointerMoved(pos2(edge + 240.0, start.y))); + h.run_steps(2); + let during = dock_width(h.state()); + let drawn = crate::panels::dock_panel_width(&h.ctx); + assert!((during - 440.0).abs() < 1.0, "the model stops at the 440-point minimum, got {during}"); + assert!((drawn - (during + rail)).abs() < 2.0, "the panel follows the stored width, got {drawn} for {during}+{rail}"); + h.event(Event::PointerButton { pos: pos2(edge + 240.0, start.y), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(1); + let after = dock_width(h.state()); + assert!((after - during).abs() < 1.0, "the release keeps the model width, got {after} then {during}"); + let drawn = crate::panels::dock_panel_width(&h.ctx); + assert!((drawn - (after + rail)).abs() < 2.0, "the release frame follows the stored width, got {drawn} for {after}+{rail}"); +} + +/// A workspace replacement during a drag invalidates the stored gesture before it can write. +#[test] +fn replacing_the_workspace_cancels_the_dock_drag() { + for release_first in [false, true] { + let mut app = app(); + app.run("window.panel.move", json!({"panel":"swatches","anchor":"layers"})).unwrap(); + let mut h = dock_edge_harness(app, vec2(1280.0, 800.0)); + let start = begin_outer_resize(&mut h); + h.event(Event::PointerMoved(start + vec2(20.0, 0.0))); + h.run_steps(1); + let mut replacement = legacy(h.state()); + dock_columns_mut(replacement.root.as_mut().expect("root")).expect("end dock")[0].width = 520.0; + let generation = h.state().ui.docking_generation; + crate::dock::apply(h.state_mut(), &json!({"docking": Workspace::new(replacement)})); + assert_eq!(h.state().ui.docking_generation, generation.wrapping_add(1)); + assert!((dock_width(h.state()) - 520.0).abs() < 0.5, "the installed baseline is known before any frame"); + if release_first { + release_outer_resize(&mut h, start + vec2(100.0, 0.0)); + } else { + h.run_steps(1); + } + assert!(!crate::panels::dock_edge_drag_active(&h.ctx), "the first frame clears the stale gesture"); + assert!((dock_width(h.state()) - 520.0).abs() < 0.5, "the first frame must not overwrite the replacement"); + if !release_first { + release_outer_resize(&mut h, start + vec2(100.0, 0.0)); + } + h.run_steps(2); + assert!((dock_width(h.state()) - 520.0).abs() < 0.5, "release and idle retain the installed width"); + } +} + +/// A window too narrow for the column minima does not panic while resizing and keeps the panel +/// inside the available space, also when the window shrinks to it in the middle of a drag. +#[test] +fn constrained_width_does_not_panic_while_resizing() { + let two_columns = || { + let mut app = app(); + let mut layout = legacy(&app); + let used: std::collections::HashSet = layout.panels().into_iter().map(|panel| panel.to_string()).collect(); + let extra = PANELS.iter().map(|(id, _, _)| *id).find(|id| !used.contains(*id)).expect("a free panel id"); + { + let root = layout.root.as_mut().expect("the legacy layout has a root"); + let dock = match root { + Node::Split { second, .. } => second.as_mut(), + _ => root, + }; + let Node::Dock { columns, .. } = dock else { panic!("the end dock is missing") }; + columns.push(Column::new(vec![craft_ui::docking::Group::new(vec![extra.to_owned()], 0)], 180.0)); + } + app.ui.docking = Some(Workspace::new(layout)); + app + }; + // A drag started in a wide window is cancelled once the shrunk window cannot fit the columns. + let mut h = dock_edge_harness(two_columns(), vec2(1280.0, 600.0)); + let start = begin_outer_resize(&mut h); + h.event(Event::PointerMoved(start + vec2(-30.0, 0.0))); + h.run_steps(1); + assert!(crate::panels::dock_edge_drag_active(&h.ctx), "the drag is held in the wide window"); + let stored: Vec = end_columns(h.state()).iter().map(|column| column.width).collect(); + h.set_size(vec2(300.0, 600.0)); + h.event(Event::PointerMoved(pos2(200.0, 300.0))); + h.run_steps(3); + assert!(!crate::panels::dock_edge_drag_active(&h.ctx), "shrinking the window below the column minima cancels the held drag"); + let drawn = crate::panels::dock_panel_width(&h.ctx); + assert!(drawn <= 80.0, "the dock stays within the shrunk window mid-drag, got {drawn}"); + let widths: Vec = end_columns(h.state()).iter().map(|column| column.width).collect(); + assert_eq!(widths, stored, "the cancel keeps the stored column widths"); + h.event(Event::PointerButton { pos: pos2(200.0, 300.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert!(crate::panels::dock_panel_width(&h.ctx) <= 80.0, "the release after the cancel keeps the dock in the window"); + let widths: Vec = end_columns(h.state()).iter().map(|column| column.width).collect(); + assert_eq!(widths, stored, "the release after the cancel keeps the stored column widths"); + + let mut h = dock_edge_harness(two_columns(), vec2(300.0, 600.0)); + let drawn = crate::panels::dock_panel_width(&h.ctx); + assert!(drawn <= 80.0, "the dock stays within the narrow window, got {drawn}"); + let start = outer_handle(&h).center(); + let edge = start.x; + h.event(Event::PointerMoved(start)); + h.run_steps(1); + h.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerMoved(pos2(edge + 40.0, 300.0))); + h.run_steps(2); + h.event(Event::PointerButton { pos: pos2(edge + 40.0, 300.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(crate::panels::dock_panel_width(&h.ctx) <= 80.0, "the panel stays within the narrow window after release"); +} + +/// The rendered dock-edge resize handle's interaction rectangle. +fn outer_handle(h: &Harness<'static, PhotocraftApp>) -> egui::Rect { + h.ctx.read_response(egui::Id::unique("dock-edge-handle")).expect("the rendered resize handle").rect +} + +/// The rectangle the dock-edge panel actually allocated on the last frame. +fn allocated_dock(h: &Harness<'static, PhotocraftApp>) -> egui::Rect { + h.ctx.data(|data| data.get_temp::(egui::Id::unique("photo-dock-panel-rect")).expect("the allocated dock rectangle")) +} + +/// Presses on the dock-edge handle, asserts the drag started that frame and returns the press +/// position. +fn begin_outer_resize(h: &mut Harness<'static, PhotocraftApp>) -> Pos2 { + let start = outer_handle(h).center(); + h.event(Event::PointerMoved(start)); + h.run_steps(1); + h.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(crate::panels::dock_edge_drag_active(&h.ctx), "Sense::drag starts on the press frame"); + start +} + +/// Releases the pointer at `pos` with no preceding move, so the release alone carries the final +/// position. +fn release_outer_resize(h: &mut Harness<'static, PhotocraftApp>, pos: Pos2) { + // No preceding PointerMoved: the release event alone supplies the final position. + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(1); +} + +/// An app whose saved workspace has one end-dock column per width, each holding one panel; iconic +/// columns get distinct expanded widths so tests can check they are preserved. +fn app_with_columns(widths: &[f32], iconic: bool) -> PhotocraftApp { + assert!(widths.len() <= PANELS.len()); + let columns = widths + .iter() + .zip(PANELS.iter()) + .enumerate() + .map(|(index, (width, (id, _, _)))| { + let mut column = Column::new(vec![craft_ui::docking::Group::new(vec![(*id).to_owned()], 0)], *width); + if iconic { + column.iconic = true; + column.iconic_width = Some(*width); + column.width = 290.0 + index as f32; + } + column + }) + .collect(); + let root = with_canvas(Node::Dock { side: Side::End, columns }, widths.iter().sum::().min(520.0)); + let mut app = app(); + app.ui.docking = Some(Workspace::new(Layout { root: Some(root), floating: Vec::new() })); + assert!(valid_workspace(app.ui.docking.as_ref().unwrap()), "fixtures must be accepted saved workspaces"); + app +} + +/// The end dock's columns in the customized workspace. +fn end_columns(app: &PhotocraftApp) -> &[Column] { + let Some(Node::Dock { columns, .. }) = lay(app).root.as_ref().and_then(end_dock_node) else { panic!("the end dock is missing") }; + columns +} + +/// A request equal to the current total still lifts an undersized column to its minimum. +#[test] +fn same_total_requests_normalize_each_populated_column() { + let mut app = app_with_columns(&[290.0, 180.0], false); + set_dock_width(&mut app, 470.0); + assert!((dock_width(&app) - 470.0).abs() < 0.5); + assert!(end_columns(&app).iter().all(|column| column.width >= MIN_COLUMN_WIDTH)); +} + +/// Redistribution reaches an attainable total even when more than eight columns saturate in turn. +#[test] +fn redistribution_converges_with_more_than_eight_saturating_columns() { + let mut app = app_with_columns(&[221.0, 800221.0, 889109.75, 900220.75, 901807.9, 902072.25, 902124.94, 902137.9, 902141.9, 902242.4], false); + set_dock_width(&mut app, 2300.5); + assert!((dock_width(&app) - 2300.5).abs() < 0.5, "attainable target, got {}", dock_width(&app)); + assert!(end_columns(&app).iter().all(|column| column.width >= MIN_COLUMN_WIDTH)); +} + +/// Width an iconic column cannot take past its cap goes to the expanded column, whether the cap +/// was already reached or is reached by this request. +#[test] +fn mixed_iconic_caps_redistribute_both_existing_and_new_saturation() { + for iconic_width in [100.0, ICONIC_MAX_WIDTH] { + let mut app = app_with_columns(&[290.0, 220.0], false); + let first = &mut dock_columns_mut(app.ui.docking.as_mut().unwrap().layout.root.as_mut().unwrap()).unwrap()[0]; + first.iconic = true; + first.iconic_width = Some(iconic_width); + assert!((set_end_dock_total(&mut app, 800.0).unwrap() - 800.0).abs() < 0.5); + assert_eq!(end_columns(&app)[0].iconic_width, Some(ICONIC_MAX_WIDTH)); + assert_eq!(end_columns(&app)[0].width, 290.0, "iconic resizing preserves expanded width"); + assert!((end_columns(&app)[1].width - 560.0).abs() < 0.5); + } +} + +/// An all-iconic dock stops at the summed iconic minimum and cap, and keeps every expanded width. +#[test] +fn all_iconic_totals_stop_at_both_bounds_without_losing_expanded_widths() { + let mut app = app_with_columns(&[100.0, 200.0], true); + let expanded: Vec<_> = end_columns(&app).iter().map(|column| column.width).collect(); + for (requested, expected) in [(1000.0, 480.0), (1.0, 72.0), (300.0, 300.0)] { + assert!((set_end_dock_total(&mut app, requested).unwrap() - expected).abs() < 0.5); + let stored: f32 = end_columns(&app).iter().map(display_width).sum(); + assert!((stored - expected).abs() < 1.0, "the columns store the {expected}-point total, got {stored}"); + for (column, expanded) in end_columns(&app).iter().zip(&expanded) { + assert!((ICONIC_WIDTH..=ICONIC_MAX_WIDTH).contains(&display_width(column))); + assert_eq!(column.width, *expanded); + } + } +} + +/// The end-dock setter reports a same-width legacy request as a no-op and rejects invalid, +/// locked and empty cases without changing the workspace. +#[test] +fn end_dock_setter_reports_legacy_noop_and_rejects_without_mutation() { + let mut app = app(); + let current = dock_width(&app); + assert_eq!(set_end_dock_total(&mut app, current), Some(current)); + assert!(app.ui.docking.is_none(), "same-width legacy requests must not customize"); + for rejected in [0.0, -1.0, f32::NAN, f32::INFINITY] { + assert_eq!(set_end_dock_total(&mut app, rejected), None); + assert!(app.ui.docking.is_none()); + } + app.session.prefs.edit(|prefs| prefs.workspace_locked = true); + assert_eq!(set_end_dock_total(&mut app, current + 100.0), None); + assert!(app.ui.docking.is_none()); + app.session.prefs.edit(|prefs| prefs.workspace_locked = false); + assert_eq!(set_end_dock_total(&mut app, 400.0), Some(400.0)); + assert!((dock_width(&app) - 400.0).abs() < 0.5); + let mut empty = app_with_columns(&[], false); + let before = empty.ui.docking.clone(); + assert_eq!(set_end_dock_total(&mut empty, 400.0), None); + assert_eq!(empty.ui.docking, before); +} + +/// Idle frames draw the stored 220-point width; a gesture, even without motion, applies the +/// 250-point resize minimum. +#[test] +fn an_idle_expanded_dock_uses_its_stored_width_not_the_gesture_minimum() { + let mut h = dock_edge_harness(app_with_columns(&[220.0], false), vec2(1280.0, 800.0)); + let rail = if h.state().ui.panels.rail { 36.0 } else { 0.0 }; + assert!((allocated_dock(&h).width() - 220.0 - rail).abs() < 1.0); + assert_eq!(dock_width(h.state()), 220.0); + let start = begin_outer_resize(&mut h); + assert_eq!(dock_width(h.state()), 220.0, "the press records the existing idle width"); + release_outer_resize(&mut h, start); + assert_eq!(dock_width(h.state()), 250.0, "even an unmoved gesture applies the resize minimum"); + assert!((allocated_dock(&h).width() - 250.0 - rail).abs() < 1.0); + h.run_steps(2); + assert_eq!(dock_width(h.state()), 250.0, "idle keeps the normalized gesture result"); +} + +/// A release with no preceding move updates the model and the allocated panel on that frame, +/// counting the rail once, in both directions, both rail widths and with the rail hidden. +#[test] +fn release_only_position_updates_model_and_actual_geometry_on_that_frame() { + for dir in [crate::direction::Dir::Ltr, crate::direction::Dir::Rtl] { + let _direction = crate::direction::direction_scope(dir); + for theme in [crate::theme::ThemeKind::ProMedium, crate::theme::ThemeKind::Classic] { + for rail in [false, true] { + let mut app = app_with_columns(&[400.0], false); + app.ui.panels.rail = rail; + app.ui.theme = theme; + let rw = if rail { if theme.is_pro() { 36.0 } else { 44.0 } } else { 0.0 }; + let mut h = dock_panel_harness(app, vec2(1280.0, 800.0), theme); + let start = begin_outer_resize(&mut h); + let sign = if crate::direction::is_rtl() { 1.0 } else { -1.0 }; + h.event(Event::PointerMoved(start + vec2(sign * 30.0, 0.0))); + h.run_steps(1); + assert!((dock_width(h.state()) - 430.0).abs() < 0.5); + assert!((allocated_dock(&h).width() - 430.0 - rw).abs() < 1.0); + release_outer_resize(&mut h, start + vec2(sign * 80.0, 0.0)); + assert!(!crate::panels::dock_edge_drag_active(&h.ctx)); + assert!((dock_width(h.state()) - 480.0).abs() < 0.5, "the release-only position is applied immediately"); + let released = allocated_dock(&h); + assert!((released.width() - 480.0 - rw).abs() < 1.0, "the rail is counted once"); + h.run_steps(2); + assert!((allocated_dock(&h).width() - released.width()).abs() < 0.5, "idle does not jump"); + } + } + } +} + +/// A dock-edge harness `width` points wide with the Pro single-column toolbox on the right, the +/// rail and a stored 520-point dock column, after the frames that draw it. +fn narrow_dock_harness(width: f32) -> Harness<'static, PhotocraftApp> { + let mut app = app_with_columns(&[400.0], false); + app.ui.panels.rail = true; + app.ui.panels.toolbar_double = false; + app.ui.panels.toolbar_side = crate::state::ToolbarSide::Right; + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(width, 600.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium); + ready = true; + return; + } + crate::panels::dock_panel(app, ui); + crate::panels::toolbar(app, ui); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { + ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("narrow-canvas-rect"), ui.max_rect())); + }); + }, + app, + ); + h.run_steps(4); + assert_eq!(crate::panels::toolbar::toolbar_width(h.state().ui.theme.is_pro(), false), 40.0, "the Pro single-column toolbox"); + let ctx = h.ctx.clone(); + assert_eq!(control_set(h.state_mut(), &ctx, json!({"dockWidth":520.0}))["ok"], true); + h.run_steps(2); + h +} + +/// The canvas rectangle [`narrow_dock_harness`] drew on its last frame. +fn narrow_canvas(h: &Harness<'static, PhotocraftApp>) -> egui::Rect { + h.ctx.data(|data| data.get_temp::(egui::Id::unique("narrow-canvas-rect")).expect("the canvas rect")) +} + +/// The panel a dock column's control acts on; `None` for floating-window and split controls. +fn dock_hit_panel(hit: &craft_ui::docking::Hit) -> Option<&String> { + use craft_ui::docking::{Divider, Hit}; + match hit { + Hit::Tab(p) + | Hit::DragBar(p) + | Hit::Border(p) + | Hit::Overflow(p) + | Hit::ColumnBar(p) + | Hit::Collapse(p) + | Hit::StackToggle(p) + | Hit::Icon(p) + | Hit::IconGrip(p) => Some(p), + Hit::Divider(Divider::Column(p) | Divider::Group(p) | Divider::Stack(p)) => Some(p), + _ => None, + } +} + +/// Asserts that every control of the end dock's panels keeps its clipped `interact_rect`, what is +/// drawn and clickable, inside `dock`, and returns how many have a full `rect` past it. +fn dock_controls_clipped(h: &Harness<'static, PhotocraftApp>, dock: egui::Rect) -> usize { + use craft_ui::docking::DockArea; + let panels: Vec<&String> = end_columns(h.state()).iter().flat_map(|c| c.groups.iter().flat_map(|g| g.panels.iter())).collect(); + let area = area_id(); + let hits = DockArea::::hit_rects(&h.ctx, area); + let (mut drawn, mut clipped) = (0, 0); + for (hit, rect) in hits.iter().filter(|(hit, _)| dock_hit_panel(hit).is_some_and(|p| panels.contains(&p))) { + let Some(response) = h.ctx.read_response(DockArea::::hit_id(area, hit)) else { + assert!(!rect.intersect(dock).is_positive(), "{hit:?} at {rect:?} has no response"); + continue; + }; + let shown = response.interact_rect; + assert!(!shown.is_positive() || dock.expand(0.5).contains_rect(shown), "{hit:?}: interactive {shown:?} (full {rect:?}) outside {dock:?}"); + drawn += usize::from(shown.is_positive()); + clipped += usize::from(!dock.expand(2.0).contains_rect(*rect)); + } + assert!(drawn > 0, "the dock drew controls: {hits:?}"); + clipped +} + +/// `dockWidth` stores the requested model width even when a narrow window draws the dock +/// narrower: in one frame the model keeps 520, the drawn dock column fits in 364 points and the +/// canvas keeps its 200, and a wider window draws the stored width again. +#[test] +fn a_narrow_window_draws_a_stored_dock_width_narrower_without_losing_it() { + let mut h = narrow_dock_harness(640.0); + let canvas = narrow_canvas(&h); + let dock = allocated_dock(&h); + let model = dock_width(h.state()); + assert!((model - 520.0).abs() < 0.5, "the model keeps the request, got {model}"); + assert!(dock.width() - 36.0 <= 364.5, "the drawn dock column fits beside the toolbox and canvas, got {dock:?}"); + assert!(canvas.width() >= 199.5, "the canvas keeps its 200-point minimum, got {canvas:?} beside {dock:?}"); + assert!(!canvas.intersect(dock).is_positive(), "the dock never overlaps the canvas: {canvas:?}, {dock:?}"); + // The fitted column lays its chrome out inside the dock, so here nothing needs the clip. + dock_controls_clipped(&h, dock); + h.set_size(vec2(1280.0, 600.0)); + h.run_steps(3); + assert!((dock_width(h.state()) - 520.0).abs() < 0.5, "growing the window keeps the stored width"); + assert!((allocated_dock(&h).width() - 520.0 - 36.0).abs() < 1.0, "a wide window draws the stored width again, got {:?}", allocated_dock(&h)); +} + +/// With no room left for the dock column, its controls' full rects run past the panel edge and +/// the panel clip keeps what is drawn and clickable inside the dock. +#[test] +fn a_squeezed_dock_column_clips_its_controls_at_the_panel_edge() { + // The toolbox, the Pro rail (36 points) and the canvas minimum fill the window, which leaves + // the dock column only its one-point floor. + let h = narrow_dock_harness(crate::panels::toolbar::toolbar_width(true, false) + 36.0 + CANVAS_MIN_WIDTH); + let canvas = narrow_canvas(&h); + let dock = allocated_dock(&h); + assert!(!canvas.intersect(dock).is_positive(), "the dock never overlaps the canvas: {canvas:?}, {dock:?}"); + // Asserts that some control's full rect overflows the dock while every clipped one stays inside. + let clipped = dock_controls_clipped(&h, dock); + assert!(clipped > 0, "a squeezed column has chrome wider than the dock that the clip cuts off, in {dock:?}"); +} + +/// A queued external width cancels a held or just-released dock-edge drag and is drawn at its +/// actual width on the first frame that processes it. +#[test] +fn external_width_requests_supersede_held_and_release_first_gestures() { + for release_first in [false, true] { + let mut h = dock_edge_harness(app_with_columns(&[400.0], false), vec2(1280.0, 800.0)); + let start = begin_outer_resize(&mut h); + h.event(Event::PointerMoved(start + vec2(30.0, 0.0))); + h.run_steps(1); + let ctx = h.ctx.clone(); + assert_eq!(control_set(h.state_mut(), &ctx, json!({"dockWidth":520.0}))["ok"], true); + assert!(!crate::panels::dock_edge_drag_active(&h.ctx), "the external request invalidates the gesture before another frame"); + if release_first { + release_outer_resize(&mut h, start + vec2(100.0, 0.0)); + } else { + h.run_steps(1); + } + assert!((dock_width(h.state()) - 520.0).abs() < 0.5, "the request is installed on its first frame"); + let rail = if h.state().ui.panels.rail { 36.0 } else { 0.0 }; + assert!( + (allocated_dock(&h).width() - 520.0 - rail).abs() < 1.0, + "release_first={release_first}: the FIRST processing frame allocates the requested model width plus one rail, got {:?}", + allocated_dock(&h), + ); + if !release_first { + h.event(Event::PointerMoved(start + vec2(100.0, 0.0))); + h.run_steps(1); + assert!((dock_width(h.state()) - 520.0).abs() < 0.5, "later held movement cannot restore the old width"); + release_outer_resize(&mut h, start + vec2(140.0, 0.0)); + } + h.run_steps(2); + assert!((dock_width(h.state()) - 520.0).abs() < 0.5); + } +} + +/// Narrowing the window below the iconic minimum cancels an active resize without committing the +/// stale pointer width, held or release-first, and widening restores the expanded width. +#[test] +fn active_iconic_resize_is_cancelled_when_the_window_narrows() { + for release_first in [false, true] { + let mut h = dock_edge_harness(app_with_columns(&[100.0], true), vec2(1280.0, 800.0)); + let start = begin_outer_resize(&mut h); + h.event(Event::PointerMoved(start - vec2(40.0, 0.0))); + h.run_steps(1); + let before = dock_width(h.state()); + let expanded = end_columns(h.state())[0].width; + assert!((before - 140.0).abs() < 0.5); + h.set_size(vec2(300.0, 600.0)); + if release_first { + release_outer_resize(&mut h, start + vec2(100.0, 0.0)); + } else { + h.event(Event::PointerMoved(start + vec2(100.0, 0.0))); + h.run_steps(1); + } + assert!(!crate::panels::dock_edge_drag_active(&h.ctx)); + assert_eq!(dock_width(h.state()), before, "narrowing cannot commit the stale pointer width"); + assert!(allocated_dock(&h).width() <= 44.5, "the allocated panel remains bounded"); + if !release_first { + release_outer_resize(&mut h, start + vec2(140.0, 0.0)); + } + h.set_size(vec2(1280.0, 800.0)); + h.run_steps(2); + assert_eq!(dock_width(h.state()), before); + assert_eq!(end_columns(h.state())[0].width, expanded); + } +} + +/// Several iconic columns disable resizing when the window cannot fit their combined minimum. +#[test] +fn multiple_iconic_columns_disable_resizing_below_their_combined_minimum() { + let mut h = dock_edge_harness(app_with_columns(&[100.0, 100.0], true), vec2(342.0, 600.0)); + let original = dock_width(h.state()); + let start = outer_handle(&h).center(); + h.event(Event::PointerMoved(start)); + h.run_steps(1); + h.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(!crate::panels::dock_edge_drag_active(&h.ctx), "50 available points cannot fit two 36-point columns"); + h.event(Event::PointerMoved(start + vec2(100.0, 0.0))); + h.run_steps(1); + release_outer_resize(&mut h, start + vec2(120.0, 0.0)); + assert_eq!(dock_width(h.state()), original); + h.set_size(vec2(1280.0, 800.0)); + h.run_steps(2); + assert_eq!(dock_width(h.state()), original, "widening retains the pre-constraint iconic widths"); +} + +/// With the dock, toolbar and canvas composed in a narrow window, the canvas keeps its minimum +/// width and the model keeps its column minimums, in both directions and themes, with and without +/// the rail. +#[test] +fn constrained_composed_layout_reserves_the_canvas_with_or_without_a_rail() { + for dir in [crate::direction::Dir::Ltr, crate::direction::Dir::Rtl] { + let _direction = crate::direction::direction_scope(dir); + for theme in [crate::theme::ThemeKind::ProMedium, crate::theme::ThemeKind::Classic] { + for rail in [false, true] { + let mut app = app_with_columns(&[290.0, 220.0], false); + app.ui.panels.rail = rail; + app.ui.theme = theme; + app.ui.panels.toolbar_side = if crate::direction::is_rtl() { crate::state::ToolbarSide::Left } else { crate::state::ToolbarSide::Right }; + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(400.0, 600.0)).with_step_dt(1.0 / 60.0).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + PhotocraftApp::setup_context(ui.ctx(), theme); + ready = true; + return; + } + crate::panels::dock_panel(app, ui); + crate::panels::toolbar(app, ui); + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { + ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("constrained-canvas-rect"), ui.max_rect())); + }); + }, + app, + ); + h.run_steps(4); + let assert_geometry = |h: &Harness<'static, PhotocraftApp>| { + let canvas = h.ctx.data(|data| data.get_temp::(egui::Id::unique("constrained-canvas-rect")).unwrap()); + assert!(canvas.width() >= 199.5, "rail={rail}, dir={dir:?}: canvas {canvas:?}, dock {:?}", allocated_dock(h)); + assert!((dock_width(h.state()) - 510.0).abs() < 0.5, "the constrained display does not corrupt model minima"); + assert!(allocated_dock(h).width() <= 144.5, "actual allocation, not requested width"); + }; + assert_geometry(&h); + let start = outer_handle(&h).center(); + h.event(Event::PointerMoved(start)); + h.run_steps(1); + h.event(Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + assert!(!crate::panels::dock_edge_drag_active(&h.ctx)); + release_outer_resize(&mut h, start + vec2(60.0, 0.0)); + assert_geometry(&h); + } + } + } +} + +/// A queued width is drawn on its first frame while native migration still waits for the +/// canvas; the native state is consumed once. +#[test] +fn queued_external_width_precedes_but_does_not_eagerly_consume_native_migration() { + let mut app = app(); + app.last_canvas_rect = egui::Rect::NOTHING; + let mut h = dock_edge_harness(app, vec2(1280.0, 800.0)); + assert!(!h.state().last_canvas_rect.is_positive(), "the dock-only harness has not laid out a canvas"); + assert!(h.state().ui.docking.is_none()); + let key = crate::panels::panel_state_id(&h.ctx, "dock"); + let state = egui::PanelState { outer_rect: egui::Rect::from_min_size(egui::pos2(900.0, 0.0), vec2(380.0, 700.0)) }; + h.ctx.data_mut(|data| data.insert_persisted(key, state)); + h.run_steps(1); + assert!(h.state().ui.docking.is_none(), "native migration still waits for canvas readiness"); + assert!(h.ctx.data_mut(|data| data.get_persisted::(key)).is_some()); + crate::panels::request_dock_width(&h.ctx, 520.0); + h.run_steps(1); + assert!((dock_width(h.state()) - 520.0).abs() < 0.5, "the explicit request takes precedence over the old native width"); + let rail = if h.state().ui.panels.rail { 36.0 } else { 0.0 }; + assert!((allocated_dock(&h).width() - 520.0 - rail).abs() < 1.0, "first-frame allocation uses that same width"); + assert!(h.ctx.data_mut(|data| data.get_persisted::(key)).is_none(), "the migrated state is consumed once"); + h.run_steps(2); + assert!((dock_width(h.state()) - 520.0).abs() < 0.5); +} + +/// Stores a native dock `PanelState` `width` points wide, as earlier versions saved it, and +/// returns its key. +fn remember_native_width_for_request_test(ctx: &egui::Context, width: f32) -> egui::Id { + let key = crate::panels::panel_state_id(ctx, "dock"); + let state = egui::PanelState { outer_rect: egui::Rect::from_min_size(pos2(900.0, 0.0), vec2(width, 700.0)) }; + ctx.data_mut(|data| data.insert_persisted(key, state)); + key +} + +/// With the canvas already laid out, an explicit same-width request retires native migration +/// without customizing the legacy workspace, in both layouts and with the workspace locked. +#[test] +fn explicit_legacy_noop_width_supersedes_native_migration_with_ready_canvas() { + for compact in [false, true] { + for locked in [false, true] { + let mut app = app(); + app.session.prefs.edit(|prefs| prefs.workspace_locked = locked); + let mut h = if compact { dock_edge_harness(app, vec2(1280.0, 800.0)) } else { harness(app, vec2(1280.0, 800.0)) }; + assert!(h.state().last_canvas_rect.is_positive()); + assert!(h.state().ui.docking.is_none()); + let requested = dock_width(h.state()); + let key = remember_native_width_for_request_test(&h.ctx, 380.0); + let ctx = h.ctx.clone(); + assert_eq!(control_set(h.state_mut(), &ctx, json!({"dockWidth":requested}))["ok"], true); + h.run_steps(1); + assert_eq!(dock_width(h.state()), requested, "compact={compact}, locked={locked}: migration cannot override an explicit legacy no-op"); + assert!(h.state().ui.docking.is_none(), "a same-width request must not customize the legacy workspace"); + assert!(h.ctx.data_mut(|data| data.get_persisted::(key)).is_none()); + assert!(h.ctx.data(|data| data.get_temp::(crate::panels::dock_width_id())).is_none()); + h.run_steps(2); + assert_eq!(dock_width(h.state()), requested); + assert!(h.state().ui.docking.is_none()); + } + } +} + +/// An explicit same-width request made before the canvas is ready still prevents a later +/// migration from applying the saved native width. +#[test] +fn explicit_legacy_noop_width_supersedes_native_migration_after_canvas_becomes_ready() { + for locked in [false, true] { + let mut app = app(); + app.last_canvas_rect = egui::Rect::NOTHING; + app.session.prefs.edit(|prefs| prefs.workspace_locked = locked); + let mut h = dock_edge_harness(app, vec2(1280.0, 800.0)); + let requested = dock_width(h.state()); + let key = remember_native_width_for_request_test(&h.ctx, 380.0); + let ctx = h.ctx.clone(); + assert_eq!(control_set(h.state_mut(), &ctx, json!({"dockWidth":requested}))["ok"], true); + h.run_steps(1); + assert!(!h.state().last_canvas_rect.is_positive()); + assert_eq!(dock_width(h.state()), requested); + assert!(h.state().ui.docking.is_none()); + let native_retained_after_request = h.ctx.data_mut(|data| data.get_persisted::(key)).is_some(); + assert!(h.ctx.data(|data| data.get_temp::(crate::panels::dock_width_id())).is_none()); + h.state_mut().last_canvas_rect = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 600.0)); + h.run_steps(1); + assert_eq!(dock_width(h.state()), requested, "locked={locked}: later canvas readiness cannot revive the superseded native width"); + assert!(!native_retained_after_request, "consuming the explicit request retires native migration even before canvas readiness"); + assert!(h.state().ui.docking.is_none(), "the legacy no-op still must not customize the workspace"); + assert!(h.ctx.data_mut(|data| data.get_persisted::(key)).is_none()); + } +} + +/// An invalid workspace defers both the queued request and the native state until recovery, +/// after which the explicit request wins. +#[test] +fn explicit_width_request_preserves_queue_and_native_state_until_invalid_workspace_recovery() { + // The current width (a legacy no-op) and a changed one. + for changed in [false, true] { + let mut h = dock_edge_harness(app(), vec2(1280.0, 800.0)); + let requested = if changed { 520.0 } else { dock_width(h.state()) }; + let key = remember_native_width_for_request_test(&h.ctx, 380.0); + let invalid = Workspace::new(Layout { root: None, floating: Vec::new() }); + assert!(!valid_workspace(&invalid)); + h.state_mut().ui.docking = Some(invalid.clone()); + let ctx = h.ctx.clone(); + assert_eq!(control_set(h.state_mut(), &ctx, json!({"dockWidth":requested}))["ok"], true); + apply_pending_dock_width(h.state_mut(), &ctx); + assert_eq!(h.state().ui.docking, Some(invalid)); + assert_eq!(h.ctx.data(|data| data.get_temp::(crate::panels::dock_width_id())), Some(requested)); + // The rectangle `remember_native_width_for_request_test` saved, in both cases. + assert_eq!( + h.ctx.data_mut(|data| data.get_persisted::(key)).map(|state| state.outer_rect), + Some(egui::Rect::from_min_size(pos2(900.0, 0.0), vec2(380.0, 700.0))), + "changed={changed}: neither queued request nor native state is consumed or changed before recovery" + ); + h.run_steps(1); + assert!( + (dock_width(h.state()) - requested).abs() < 0.5, + "changed={changed}: the restored workspace honors the explicit request instead of the saved native width, got {}", + dock_width(h.state()) + ); + if !changed { + assert!(h.state().ui.docking.is_none(), "the legacy no-op does not customize the workspace"); + } + assert!(h.ctx.data(|data| data.get_temp::(crate::panels::dock_width_id())).is_none(), "changed={changed}: the queued request is consumed"); + assert!(h.ctx.data_mut(|data| data.get_persisted::(key)).is_none(), "changed={changed}: the native state is retired"); + } +} + +/// A consumed request retires the native state even when it is clamped or the dock is empty. +#[test] +fn explicit_width_requests_retire_native_state_even_when_clamped_or_empty() { + for empty in [false, true] { + let mut h = dock_edge_harness(if empty { app_with_columns(&[], false) } else { app() }, vec2(1280.0, 800.0)); + let before = h.state().ui.docking.clone(); + let key = remember_native_width_for_request_test(&h.ctx, 380.0); + let ctx = h.ctx.clone(); + assert_eq!(control_set(h.state_mut(), &ctx, json!({"dockWidth":20}))["ok"], true); + apply_pending_dock_width(h.state_mut(), &ctx); + assert!(h.ctx.data(|data| data.get_temp::(crate::panels::dock_width_id())).is_none()); + assert!( + h.ctx.data_mut(|data| data.get_persisted::(key)).is_none(), + "an accepted explicit request supersedes migration even when empty={empty}" + ); + if empty { + assert_eq!(h.state().ui.docking, before, "an empty dock still has no width to change"); + } else { + assert_eq!(dock_width(h.state()), 250.0, "the existing request clamp remains unchanged"); + } + } +} + +/// Without an accepted request, native migration still waits for the canvas and then applies +/// the saved width once. +#[test] +fn native_migration_still_waits_and_runs_without_an_accepted_explicit_request() { + for rejected in [false, true] { + let mut app = app(); + app.last_canvas_rect = egui::Rect::NOTHING; + let mut h = dock_edge_harness(app, vec2(1280.0, 800.0)); + let key = remember_native_width_for_request_test(&h.ctx, 380.0); + if rejected { + let ctx = h.ctx.clone(); + assert_eq!(control_set(h.state_mut(), &ctx, json!({"dockWidth":"not a width"}))["ok"], false); + } + assert!(h.ctx.data(|data| data.get_temp::(crate::panels::dock_width_id())).is_none()); + h.run_steps(1); + assert!(h.state().ui.docking.is_none()); + assert!(h.ctx.data_mut(|data| data.get_persisted::(key)).is_some(), "absent/rejected requests do not discard a pending migration"); + h.state_mut().last_canvas_rect = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 600.0)); + h.run_steps(1); + assert_eq!(dock_width(h.state()), 380.0); + assert!(h.state().ui.docking.is_some()); + assert!(h.ctx.data_mut(|data| data.get_persisted::(key)).is_none(), "the unchanged native migration consumes its state once"); + } +} diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index da8500f535..a8ed212b72 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -1,8 +1,20 @@ use super::options_bar::reveal_focused_control; use super::{Align2, Color32, PhotocraftApp, Pos2, Rect, Sense, Stroke, StrokeKind, Tokens, Tool, c32, icons, json, pos2, vec2}; +use crate::state::ToolbarSide; // ----------------------------------------------------------------------------- toolbar +/// The toolbar's single-column width and its second column's button width, in points. +pub(crate) fn toolbar_columns(pro: bool) -> (f32, f32) { + if pro { (40.0, 30.0) } else { (50.0, 36.0) } +} + +/// The toolbar panel's width in points: one column, or two when the header chevron asks for them. +pub(crate) fn toolbar_width(pro: bool, double: bool) -> f32 { + let (w1, bx) = toolbar_columns(pro); + if double { w1 + bx + 2.0 } else { w1 } +} + /// Tool groups separated by hairlines, Photoshop order. /// Photoshop toolbar: divider-separated sections of slots; each slot is a flyout group whose button /// shows the group's last-used tool. @@ -105,7 +117,7 @@ pub(crate) fn more_flyout_open(ctx: &egui::Context) -> bool { /// Right-click on the "…" button opens a flyout with one row, "Edit Toolbar…", drawn like a tool /// flyout. The row runs `edit.toolbar` and closes the flyout; Escape or a press outside closes it /// without running anything. -fn more_slot_flyout(app: &mut PhotocraftApp, ui: &mut egui::Ui, button: &egui::Response, t: &Tokens) { +fn more_slot_flyout(app: &mut PhotocraftApp, ui: &mut egui::Ui, button: &egui::Response, t: &Tokens, side: ToolbarSide) { let open_id = more_flyout_id(); let open = ui.data(|d| d.get_temp::(open_id)).unwrap_or(false); if button.secondary_clicked() { @@ -116,7 +128,7 @@ fn more_slot_flyout(app: &mut PhotocraftApp, ui: &mut egui::Ui, button: &egui::R if !open { return; } - let (pivot, pos) = if crate::direction::is_rtl() { + let (pivot, pos) = if side == ToolbarSide::Right { (egui::Align2::RIGHT_BOTTOM, button.rect.left_bottom() - vec2(6.0, 0.0)) } else { (egui::Align2::LEFT_BOTTOM, button.rect.right_bottom() + vec2(6.0, 0.0)) @@ -150,353 +162,369 @@ fn more_slot_flyout(app: &mut PhotocraftApp, ui: &mut egui::Ui, button: &egui::R } } +/// The tool palette panel, on the side `panels.toolbar_side` resolves to, with its width +/// toggle and Move Toolbar header buttons. pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - let (w1, bx, m) = if t.pro { (40.0, 30.0, 5i8) } else { (50.0, 36.0, 7i8) }; + let (_, bx) = toolbar_columns(t.pro); + let m = if t.pro { 5i8 } else { 7i8 }; let sections = visible_sections(&app.session.prefs().toolbar.hidden); // Two columns when the header chevron asks for them; a column that doesn't fit scrolls. let double = app.ui.panels.toolbar_double; - let w = if double { w1 + bx + 2.0 } else { w1 }; - crate::direction::start_panel("toolbar") - .resizable(false) - .exact_size(w) - .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(m, 8))) - .show(ui, |ui| { - // Toolbar width is a user preference, not a Pro-only feature. - // Keep the same hit target in every theme (including RTL layouts). - let (cr, resp) = ui.allocate_exact_size(vec2(bx, 14.0), Sense::click()); - let (shrink, grow) = if crate::direction::is_rtl() { ("chevrons-right", "chevrons-left") } else { ("chevrons-left", "chevrons-right") }; + let w = toolbar_width(t.pro, double); + let side = app.ui.panels.toolbar_side.resolve(); + let panel = if side == ToolbarSide::Right { egui::Panel::right("toolbar") } else { egui::Panel::left("toolbar") }; + panel.resizable(false).exact_size(w).frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(m, 8))).show(ui, |ui| { + // Toolbar width is a user preference, not a Pro-only feature. The two header buttons share + // the narrow toolbar column (14-point targets in every theme, including RTL layouts), so + // their tooltips carry the full names. + ui.allocate_ui_with_layout(vec2(bx, 14.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 2.0; + let (cr, resp) = ui.allocate_exact_size(vec2(bx.min(14.0), 14.0), Sense::click()); + let (shrink, grow) = if side == ToolbarSide::Right { ("chevrons-right", "chevrons-left") } else { ("chevrons-left", "chevrons-right") }; icons::paint(ui, cr, if double { shrink } else { grow }, 11.0, if resp.hovered() { t.text } else { t.text_faint }); resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Toolbar"))); if resp.clicked() { app.ui.panels.toolbar_double = !double; } - ui.add_space(4.0); - // Subtle violet wash at the bottom of the toolbar. - let full = ui.max_rect(); - if !t.bevel && !t.pro && t.dark() { - let mut mesh = egui::Mesh::default(); - let r = Rect::from_min_max(pos2(full.left() - 7.0, full.bottom() - 260.0), pos2(full.right() + 7.0, full.bottom() + 8.0)); - let top = Color32::TRANSPARENT; - let bottom = Color32::from_rgba_unmultiplied(90, 70, 190, 34); - mesh.colored_vertex(r.left_top(), top); - mesh.colored_vertex(r.right_top(), top); - mesh.colored_vertex(r.right_bottom(), bottom); - mesh.colored_vertex(r.left_bottom(), bottom); - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - ui.painter().add(mesh); + let other = side.other(); + let (dock_tip, dock_icon) = match other { + ToolbarSide::Right => (tl!("Move Toolbar to the Right"), "panel-right"), + _ => (tl!("Move Toolbar to the Left"), "panel-left"), + }; + let (dr, dock) = ui.allocate_exact_size(vec2((bx - 16.0).max(14.0), 14.0), Sense::click()); + icons::paint(ui, dr, dock_icon, 11.0, if dock.hovered() { t.text } else { t.text_faint }); + dock.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, dock_tip)); + if dock.on_hover_text(dock_tip).clicked() { + app.ui.panels.toolbar_side = other; + // Persist the side as a discrete change; the dock may not be drawn this frame. + crate::dock::persist_panels(app, ui.ctx()); } - ui.spacing_mut().item_spacing = vec2(2.0, 3.0); - let flyout_id = egui::Id::unique("tool-flyout"); - let held_id = flyout_id.with("held"); - if ui.input(|i| i.pointer.any_pressed()) { - ui.data_mut(|d| d.remove::(held_id)); - } - // No tool tooltips over an open flyout, or while a button is held to open one (#4450): - // Photoshop shows none there. (The flyout is our own Area, so egui's rule for popups - // doesn't hide them.) - let tool_tips = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id)).is_none() && !ui.input(|i| i.pointer.primary_down()); - let ctx = ui.ctx().clone(); - let footer = (if t.pro { 8.0 } else { 14.0 }) - + chips_height(t.pro, t.round_chips, t.round_chips && double) - + 8.0 - + if double { bx } else { bx * 2.0 + 3.0 } - + 6.0; - // As tall as the tools, so the colour chips sit right under them (Photoshop); a column - // taller than the window scrolls and keeps the chips at the bottom. - egui::ScrollArea::vertical() - .id_salt("toolbar-columns") - .auto_shrink([false, true]) - .max_height((ui.available_height() - footer).max(0.0)) - .min_scrolled_height(0.0) - .show(ui, |ui| { - // Pro has no group dividers, so its two columns fill every row across groups. - let sections: Vec)>> = if t.pro { vec![sections.into_iter().flatten().collect()] } else { sections }; - for (si, section) in sections.iter().enumerate() { - // Photoshop 2026 draws one uninterrupted column (no group dividers). - if si > 0 && !t.pro { - ui.add_space(4.0); - let (r, _) = ui.allocate_exact_size(vec2(if double { bx * 2.0 + 2.0 } else { bx }, 1.0), Sense::hover()); - ui.painter().line_segment([r.left_center() + vec2(8.0, 0.0), r.right_center() - vec2(8.0, 0.0)], Stroke::new(1.0, t.separator)); - ui.add_space(4.0); - } - let rows: Vec<&[(usize, Vec)]> = if double { section.chunks(2).collect() } else { section.chunks(1).collect() }; - for row in rows { - ui.horizontal(|ui| { - for (slot_index, slot) in row.iter() { - let key = egui::Id::unique(("tool-slot", *slot_index)); - let tool = slot_tool(app.ui.tool, &app.ui.group_tools, slot); - let sel = slot.contains(&app.ui.tool); - let tip = match crate::tool_shortcuts::shortcut(app, tool) { - Some(sc) => format!("{} ({})", tl!(tool.label()), crate::shortcuts::pretty(&sc)), - None => tl!(tool.label()).to_string(), - }; - let resp = - icons::button_with_icon_size_tip(ui, icons::tool_icon(tool), bx, toolbar_icon_size(bx, t.pro), sel, &tip, tool_tips); - if slot.len() > 1 { - paint_toolbar_flyout_indicator(ui, &t, &resp); - } - // Plain click selects the shown tool; Alt/Option-click cycles the - // flyout slot to the next tool, as Shift+letter does for the key group. - // Prefer the primary-release event's modifiers (Alt may already be - // up), and only a release on this slot — the frame's event list is - // shared with every other widget. - let click_mods = - ui.input(|i| { - i.events - .iter() - .rev() - .find_map(|e| match e { - egui::Event::PointerButton { - pos, button: egui::PointerButton::Primary, pressed: false, modifiers, .. - } if resp.rect.contains(*pos) => Some(*modifiers), - _ => None, - }) - .unwrap_or(i.modifiers) - }); - let alt = click_mods.alt; - let modified = click_mods.alt || click_mods.shift || click_mods.ctrl || click_mods.command; - // egui's double-click ignores modifiers: a plain click after a - // modified click within max_double_click_delay still reports - // double_clicked(). Remember the previous click so Hand fit / - // Zoom 100% only run for two plain clicks. - let prev_mod_id = key.with("click-mod"); - let prev_modified = ui.data(|d| d.get_temp::(prev_mod_id)).unwrap_or(false); - let slot_click = resp.clicked() && ui.data(|d| d.get_temp::(held_id)) != Some(key); - if slot_click { - let pick = if slot.len() > 1 && alt { - let from = if slot.contains(&app.ui.tool) { app.ui.tool } else { tool }; - next_slot_tool(slot, from) - } else { - tool - }; - crate::tool_memory::select(app, pick); - } - // Double-clicking the Hand tool fits the image on screen (Photoshop). - // Modified clicks only cycle / select: a second rapid Alt-click, or a - // plain click that egui pairs with a prior modified click, must not - // count as Hand/Zoom double-click after cycling onto those tools. - let plain_double = resp.double_clicked() && !modified && !prev_modified; - if plain_double && tool == Tool::Hand { - crate::tool_memory::select(app, tool); - // With no document open there is nothing to fit. - let _ = app.run("view.fitOnScreen", json!({})); - } - if plain_double && tool == Tool::Zoom { - crate::tool_memory::select(app, tool); - let _ = app.run("view.actualPixels", json!({})); - } - if slot_click { - ui.data_mut(|d| d.insert_temp(prev_mod_id, modified)); - } - // Right-click, long-press, or press-drag away opens the flyout (Photoshop). - let held_for = - resp.is_pointer_button_down_on().then(|| ui.input(|i| i.pointer.press_start_time().map(|t0| i.time - t0))).flatten(); - if slot.len() > 1 - && let Some(seconds) = held_for - && seconds < 0.35 - { - ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(0.35 - seconds)); - } - let long_press = held_for.is_some_and(|seconds| seconds >= 0.35); - let drag_open = ui - .input(|i| tool_flyout_drag_open(resp.rect, i.pointer.press_origin(), i.pointer.hover_pos(), i.pointer.primary_down())); - // Clicking the button of its open flyout again, with either button, closes - // it (#4932); the release that ends the long press that opened it doesn't. - let open_here = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id)).is_some_and(|(k, _)| k == key); - let reclicked = open_here - && (resp.secondary_clicked() || (resp.clicked() && ui.data(|d| d.get_temp::(held_id)) != Some(key))); - if reclicked { - ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id)); - } else if slot.len() > 1 && (resp.secondary_clicked() || long_press || drag_open) { - ui.data_mut(|d| { - d.insert_temp(flyout_id, (key, resp.rect)); - if long_press || drag_open { - d.insert_temp(held_id, key); + }); + ui.add_space(4.0); + // Subtle violet wash at the bottom of the toolbar. + let full = ui.max_rect(); + if !t.bevel && !t.pro && t.dark() { + let mut mesh = egui::Mesh::default(); + let r = Rect::from_min_max(pos2(full.left() - 7.0, full.bottom() - 260.0), pos2(full.right() + 7.0, full.bottom() + 8.0)); + let top = Color32::TRANSPARENT; + let bottom = Color32::from_rgba_unmultiplied(90, 70, 190, 34); + mesh.colored_vertex(r.left_top(), top); + mesh.colored_vertex(r.right_top(), top); + mesh.colored_vertex(r.right_bottom(), bottom); + mesh.colored_vertex(r.left_bottom(), bottom); + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + ui.painter().add(mesh); + } + ui.spacing_mut().item_spacing = vec2(2.0, 3.0); + let flyout_id = egui::Id::unique("tool-flyout"); + let held_id = flyout_id.with("held"); + if ui.input(|i| i.pointer.any_pressed()) { + ui.data_mut(|d| d.remove::(held_id)); + } + // No tool tooltips over an open flyout, or while a button is held to open one (#4450): + // Photoshop shows none there. (The flyout is our own Area, so egui's rule for popups + // doesn't hide them.) + let tool_tips = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id)).is_none() && !ui.input(|i| i.pointer.primary_down()); + let ctx = ui.ctx().clone(); + let footer = (if t.pro { 8.0 } else { 14.0 }) + + chips_height(t.pro, t.round_chips, t.round_chips && double) + + 8.0 + + if double { bx } else { bx * 2.0 + 3.0 } + + 6.0; + // As tall as the tools, so the colour chips sit right under them (Photoshop); a column + // taller than the window scrolls and keeps the chips at the bottom. + egui::ScrollArea::vertical() + .id_salt("toolbar-columns") + .auto_shrink([false, true]) + .max_height((ui.available_height() - footer).max(0.0)) + .min_scrolled_height(0.0) + .show(ui, |ui| { + // Pro has no group dividers, so its two columns fill every row across groups. + let sections: Vec)>> = if t.pro { vec![sections.into_iter().flatten().collect()] } else { sections }; + for (si, section) in sections.iter().enumerate() { + // Photoshop 2026 draws one uninterrupted column (no group dividers). + if si > 0 && !t.pro { + ui.add_space(4.0); + let (r, _) = ui.allocate_exact_size(vec2(if double { bx * 2.0 + 2.0 } else { bx }, 1.0), Sense::hover()); + ui.painter().line_segment([r.left_center() + vec2(8.0, 0.0), r.right_center() - vec2(8.0, 0.0)], Stroke::new(1.0, t.separator)); + ui.add_space(4.0); + } + let rows: Vec<&[(usize, Vec)]> = if double { section.chunks(2).collect() } else { section.chunks(1).collect() }; + for row in rows { + ui.horizontal(|ui| { + for (slot_index, slot) in row.iter() { + let key = egui::Id::unique(("tool-slot", *slot_index)); + let tool = slot_tool(app.ui.tool, &app.ui.group_tools, slot); + let sel = slot.contains(&app.ui.tool); + let tip = match crate::tool_shortcuts::shortcut(app, tool) { + Some(sc) => format!("{} ({})", tl!(tool.label()), crate::shortcuts::pretty(&sc)), + None => tl!(tool.label()).to_string(), + }; + let resp = icons::button_with_icon_size_tip(ui, icons::tool_icon(tool), bx, toolbar_icon_size(bx, t.pro), sel, &tip, tool_tips); + if slot.len() > 1 { + paint_toolbar_flyout_indicator(ui, &t, &resp, side); + } + // Plain click selects the shown tool; Alt/Option-click cycles the + // flyout slot to the next tool, as Shift+letter does for the key group. + // Prefer the primary-release event's modifiers (Alt may already be + // up), and only a release on this slot — the frame's event list is + // shared with every other widget. + let click_mods = ui.input(|i| { + i.events + .iter() + .rev() + .find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers, .. } + if resp.rect.contains(*pos) => + { + Some(*modifiers) } - }); - } - if slot.len() > 1 && long_press { - // Holding a tool button selects the tool it shows, as a click would (#4453). - crate::tool_memory::select(app, tool); - ui.ctx().request_repaint(); - } - if let Some((open_key, anchor)) = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id)) - && open_key == key - { - // Beside the tool, towards the canvas. - let (pivot, pos) = if crate::direction::is_rtl() { - (egui::Align2::RIGHT_TOP, anchor.left_top() - vec2(6.0, 0.0)) - } else { - (egui::Align2::LEFT_TOP, anchor.right_top() + vec2(6.0, 0.0)) - }; - let area = egui::Area::new(key.with("flyout")).order(egui::Order::Foreground).pivot(pivot).fixed_pos(pos).show( - ui.ctx(), - |ui| { - egui::Frame::popup(ui.style()).show(ui, |ui| { - let label_w = slot - .iter() - .map(|it| { - ui.painter() - .layout_no_wrap(tl!(it.label()).to_string(), egui::FontId::proportional(12.5), t.text) - .size() - .x - }) - .fold(0.0f32, f32::max); - let fw = (label_w + 42.0 + 40.0).max(180.0); - for &item in slot.iter() { - let (r, ir) = ui.allocate_exact_size(vec2(fw, 26.0), Sense::click()); - if ir.hovered() { - ui.painter().rect_filled(r, 3.0, t.hover); - } - if item == tool { - ui.painter().rect_filled( - Rect::from_center_size(pos2(r.left() + 8.0, r.center().y), vec2(4.0, 4.0)), - 0.0, - t.text, - ); - } - icons::paint( - ui, - Rect::from_center_size(pos2(r.left() + 26.0, r.center().y), vec2(18.0, 18.0)), - icons::tool_icon(item), - 14.0, - t.icon, - ); - ui.painter().text( - pos2(r.left() + 42.0, r.center().y), - Align2::LEFT_CENTER, - tl!(item.label()), - egui::FontId::proportional(12.5), + _ => None, + }) + .unwrap_or(i.modifiers) + }); + let alt = click_mods.alt; + let modified = click_mods.alt || click_mods.shift || click_mods.ctrl || click_mods.command; + // egui's double-click ignores modifiers: a plain click after a + // modified click within max_double_click_delay still reports + // double_clicked(). Remember the previous click so Hand fit / + // Zoom 100% only run for two plain clicks. + let prev_mod_id = key.with("click-mod"); + let prev_modified = ui.data(|d| d.get_temp::(prev_mod_id)).unwrap_or(false); + let slot_click = resp.clicked() && ui.data(|d| d.get_temp::(held_id)) != Some(key); + if slot_click { + let pick = if slot.len() > 1 && alt { + let from = if slot.contains(&app.ui.tool) { app.ui.tool } else { tool }; + next_slot_tool(slot, from) + } else { + tool + }; + crate::tool_memory::select(app, pick); + } + // Double-clicking the Hand tool fits the image on screen (Photoshop). + // Modified clicks only cycle / select: a second rapid Alt-click, or a + // plain click that egui pairs with a prior modified click, must not + // count as Hand/Zoom double-click after cycling onto those tools. + let plain_double = resp.double_clicked() && !modified && !prev_modified; + if plain_double && tool == Tool::Hand { + crate::tool_memory::select(app, tool); + // With no document open there is nothing to fit. + let _ = app.run("view.fitOnScreen", json!({})); + } + if plain_double && tool == Tool::Zoom { + crate::tool_memory::select(app, tool); + let _ = app.run("view.actualPixels", json!({})); + } + if slot_click { + ui.data_mut(|d| d.insert_temp(prev_mod_id, modified)); + } + // Right-click, long-press, or press-drag away opens the flyout (Photoshop). + let held_for = + resp.is_pointer_button_down_on().then(|| ui.input(|i| i.pointer.press_start_time().map(|t0| i.time - t0))).flatten(); + if slot.len() > 1 + && let Some(seconds) = held_for + && seconds < 0.35 + { + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(0.35 - seconds)); + } + let long_press = held_for.is_some_and(|seconds| seconds >= 0.35); + let drag_open = + ui.input(|i| tool_flyout_drag_open(resp.rect, i.pointer.press_origin(), i.pointer.hover_pos(), i.pointer.primary_down())); + // Clicking the button of its open flyout again, with either button, closes + // it (#4932); the release that ends the long press that opened it doesn't. + let open_here = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id)).is_some_and(|(k, _)| k == key); + let reclicked = + open_here && (resp.secondary_clicked() || (resp.clicked() && ui.data(|d| d.get_temp::(held_id)) != Some(key))); + if reclicked { + ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id)); + } else if slot.len() > 1 && (resp.secondary_clicked() || long_press || drag_open) { + ui.data_mut(|d| { + d.insert_temp(flyout_id, (key, resp.rect)); + if long_press || drag_open { + d.insert_temp(held_id, key); + } + }); + } + if slot.len() > 1 && long_press { + // Holding a tool button selects the tool it shows, as a click would (#4453). + crate::tool_memory::select(app, tool); + ui.ctx().request_repaint(); + } + if let Some((open_key, anchor)) = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id)) + && open_key == key + { + // Beside the tool, towards the canvas. + let (pivot, pos) = if side == ToolbarSide::Right { + (egui::Align2::RIGHT_TOP, anchor.left_top() - vec2(6.0, 0.0)) + } else { + (egui::Align2::LEFT_TOP, anchor.right_top() + vec2(6.0, 0.0)) + }; + let area = + egui::Area::new(key.with("flyout")).order(egui::Order::Foreground).pivot(pivot).fixed_pos(pos).show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + let label_w = slot + .iter() + .map(|it| { + ui.painter() + .layout_no_wrap(tl!(it.label()).to_string(), egui::FontId::proportional(12.5), t.text) + .size() + .x + }) + .fold(0.0f32, f32::max); + let fw = (label_w + 42.0 + 40.0).max(180.0); + for &item in slot.iter() { + let (r, ir) = ui.allocate_exact_size(vec2(fw, 26.0), Sense::click()); + if ir.hovered() { + ui.painter().rect_filled(r, 3.0, t.hover); + } + if item == tool { + ui.painter().rect_filled( + Rect::from_center_size(pos2(r.left() + 8.0, r.center().y), vec2(4.0, 4.0)), + 0.0, t.text, ); - if let Some(sc) = crate::tool_shortcuts::shortcut(app, item) { - ui.painter().text( - pos2(r.right() - 8.0, r.center().y), - Align2::RIGHT_CENTER, - crate::shortcuts::pretty(&sc), - egui::FontId::proportional(12.0), - t.text_dim, - ); - } - let drag_release = tool_flyout_release( - r, - ui.input(|i| i.pointer.hover_pos()), - ui.input(|i| i.pointer.primary_released()), - ui.data(|d| d.get_temp::(held_id)) == Some(key), - ); - if ir.clicked() || drag_release { - crate::tool_memory::select(app, item); - ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id)); - } } - }); - }, - ); - // Any press outside the flyout and its button closes it, as in Photoshop: a - // drag on the canvas (cropping, painting) isn't a click (#4460). - let pressed_outside = ui.input(|i| { - i.pointer.any_pressed() - && i.pointer.press_origin().is_some_and(|p| !area.response.rect.contains(p) && !resp.rect.contains(p)) + icons::paint( + ui, + Rect::from_center_size(pos2(r.left() + 26.0, r.center().y), vec2(18.0, 18.0)), + icons::tool_icon(item), + 14.0, + t.icon, + ); + ui.painter().text( + pos2(r.left() + 42.0, r.center().y), + Align2::LEFT_CENTER, + tl!(item.label()), + egui::FontId::proportional(12.5), + t.text, + ); + if let Some(sc) = crate::tool_shortcuts::shortcut(app, item) { + ui.painter().text( + pos2(r.right() - 8.0, r.center().y), + Align2::RIGHT_CENTER, + crate::shortcuts::pretty(&sc), + egui::FontId::proportional(12.0), + t.text_dim, + ); + } + let drag_release = tool_flyout_release( + r, + ui.input(|i| i.pointer.hover_pos()), + ui.input(|i| i.pointer.primary_released()), + ui.data(|d| d.get_temp::(held_id)) == Some(key), + ); + if ir.clicked() || drag_release { + crate::tool_memory::select(app, item); + ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id)); + } + } + }); }); - if pressed_outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) { - ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id)); - } + // Any press outside the flyout and its button closes it, as in Photoshop: a + // drag on the canvas (cropping, painting) isn't a click (#4460). + let pressed_outside = ui.input(|i| { + i.pointer.any_pressed() + && i.pointer.press_origin().is_some_and(|p| !area.response.rect.contains(p) && !resp.rect.contains(p)) + }); + if pressed_outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id)); } } - }); - } + } + }); } - let more = icons::button(ui, "ellipsis", bx, false, tl!("Edit Toolbar…")); - if more.clicked() - && let Err(e) = crate::menus::invoke(app, &ctx, "edit.toolbar", json!({})) - { - app.ui.status = e; - app.ui.status_error = true; - } - more_slot_flyout(app, ui, &more, &t); - reveal_focused_control(ui); - }); - ui.add_space(if t.pro { 8.0 } else { 14.0 }); - // Centred in the tool column as it is before the tools scroll: a scroll bar widens the - // UI it is in, and the chips moved over by its width (#7316). - color_chips(app, ui, double, full.width()); - ui.add_space(8.0); - - let layout = if double { egui::Layout::left_to_right(egui::Align::Min) } else { egui::Layout::top_down(egui::Align::Min) }; - - ui.with_layout(layout, |ui| { - let quick_mask = app.session.active().is_some_and(|s| s.doc.quick_mask.is_some()); - if icons::button_with_icon_size_tip( - ui, - "square-dashed", - bx, - (bx * 0.52).round(), - quick_mask, - if quick_mask { tl!("Edit in Standard Mode (Q)") } else { tl!("Edit in Quick Mask Mode (Q)") }, - tool_tips, - ) - .clicked() + } + let more = icons::button(ui, "ellipsis", bx, false, tl!("Edit Toolbar…")); + if more.clicked() + && let Err(e) = crate::menus::invoke(app, &ctx, "edit.toolbar", json!({})) { - let _ = crate::menus::invoke(app, &ctx, "select.editInQuickMaskMode", json!({})); + app.ui.status = e; + app.ui.status_error = true; } - // Greyed out while Cycle is unavailable (no document in Standard, #9349): its - // list would offer nothing else either. - let cycle_enabled = crate::view_cmds::is_enabled(app, "view.screenMode.cycle").unwrap_or(true); - let sm = ui - .add_enabled_ui(cycle_enabled, |ui| { - icons::button_with_icon_size_tip(ui, "app-window", bx, (bx * 0.52).round(), false, tl!("Change Screen Mode (F)"), tool_tips) - }) - .inner; - paint_toolbar_flyout_indicator(ui, &t, &sm); + more_slot_flyout(app, ui, &more, &t, side); + reveal_focused_control(ui); + }); + ui.add_space(if t.pro { 8.0 } else { 14.0 }); + // Centred in the tool column as it is before the tools scroll: a scroll bar widens the + // UI it is in, and the chips moved over by its width (#7316). + color_chips(app, ui, double, full.width()); + ui.add_space(8.0); - // Right-click, or click and hold like the tool flyouts (#4444), lists the modes, - // like Photoshop's flyout. The release that ends a hold doesn't cycle the mode. - let held_id = sm.id.with("held"); - let was_held = ui.data(|d| d.get_temp::(held_id)).unwrap_or(false); - let held_for = sm.is_pointer_button_down_on().then(|| ui.input(|i| i.pointer.press_start_time().map(|t0| i.time - t0))).flatten(); - if let Some(seconds) = held_for - && seconds < 0.35 - { - ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(0.35 - seconds)); - } - let long_press = !was_held && held_for.is_some_and(|seconds| seconds >= 0.35); - if long_press { - ui.data_mut(|d| d.insert_temp(held_id, true)); - } else if was_held && !sm.is_pointer_button_down_on() { - ui.data_mut(|d| d.remove::(held_id)); - } - let cycle = sm.clicked() && !was_held; - if cycle { - let _ = crate::menus::invoke(app, &ctx, "view.screenMode.cycle", json!({})); - } - let open = if sm.secondary_clicked() || long_press { - Some(egui::SetOpenCommand::Bool(true)) - } else if cycle { - Some(egui::SetOpenCommand::Bool(false)) - } else { - None - }; - // The release ending the hold counts as a click; it mustn't close the list it opened. - let close = if was_held || long_press { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClick }; - egui::Popup::menu(&sm).open_memory(open).close_behavior(close).at_pointer_fixed().show(|ui| { - ui.set_min_width(220.0); - for (id, label) in [ - ("view.screenMode.standard", tl!("Standard Screen Mode")), - ("view.screenMode.fullScreenWithMenuBar", tl!("Full Screen Mode With Menu Bar")), - ("view.screenMode.fullScreen", tl!("Full Screen Mode")), - ] { - let on = crate::view_cmds::checked(app, id).unwrap_or(false); - let enabled = crate::view_cmds::is_enabled(app, id).unwrap_or(true); - if ui.add_enabled(enabled, egui::Button::selectable(on, label)).clicked() { - let _ = crate::menus::invoke(app, &ctx, id, json!({})); - ui.close(); - } + let layout = if double { egui::Layout::left_to_right(egui::Align::Min) } else { egui::Layout::top_down(egui::Align::Min) }; + + ui.with_layout(layout, |ui| { + let quick_mask = app.session.active().is_some_and(|s| s.doc.quick_mask.is_some()); + if icons::button_with_icon_size_tip( + ui, + "square-dashed", + bx, + (bx * 0.52).round(), + quick_mask, + if quick_mask { tl!("Edit in Standard Mode (Q)") } else { tl!("Edit in Quick Mask Mode (Q)") }, + tool_tips, + ) + .clicked() + { + let _ = crate::menus::invoke(app, &ctx, "select.editInQuickMaskMode", json!({})); + } + // Greyed out while Cycle is unavailable (no document in Standard, #9349): its + // list would offer nothing else either. + let cycle_enabled = crate::view_cmds::is_enabled(app, "view.screenMode.cycle").unwrap_or(true); + let sm = ui + .add_enabled_ui(cycle_enabled, |ui| { + icons::button_with_icon_size_tip(ui, "app-window", bx, (bx * 0.52).round(), false, tl!("Change Screen Mode (F)"), tool_tips) + }) + .inner; + paint_toolbar_flyout_indicator(ui, &t, &sm, side); + + // Right-click, or click and hold like the tool flyouts (#4444), lists the modes, + // like Photoshop's flyout. The release that ends a hold doesn't cycle the mode. + let held_id = sm.id.with("held"); + let was_held = ui.data(|d| d.get_temp::(held_id)).unwrap_or(false); + let held_for = sm.is_pointer_button_down_on().then(|| ui.input(|i| i.pointer.press_start_time().map(|t0| i.time - t0))).flatten(); + if let Some(seconds) = held_for + && seconds < 0.35 + { + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(0.35 - seconds)); + } + let long_press = !was_held && held_for.is_some_and(|seconds| seconds >= 0.35); + if long_press { + ui.data_mut(|d| d.insert_temp(held_id, true)); + } else if was_held && !sm.is_pointer_button_down_on() { + ui.data_mut(|d| d.remove::(held_id)); + } + let cycle = sm.clicked() && !was_held; + if cycle { + let _ = crate::menus::invoke(app, &ctx, "view.screenMode.cycle", json!({})); + } + let open = if sm.secondary_clicked() || long_press { + Some(egui::SetOpenCommand::Bool(true)) + } else if cycle { + Some(egui::SetOpenCommand::Bool(false)) + } else { + None + }; + // The release ending the hold counts as a click; it mustn't close the list it opened. + let close = if was_held || long_press { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClick }; + egui::Popup::menu(&sm).open_memory(open).close_behavior(close).at_pointer_fixed().show(|ui| { + ui.set_min_width(220.0); + for (id, label) in [ + ("view.screenMode.standard", tl!("Standard Screen Mode")), + ("view.screenMode.fullScreenWithMenuBar", tl!("Full Screen Mode With Menu Bar")), + ("view.screenMode.fullScreen", tl!("Full Screen Mode")), + ] { + let on = crate::view_cmds::checked(app, id).unwrap_or(false); + let enabled = crate::view_cmds::is_enabled(app, id).unwrap_or(true); + if ui.add_enabled(enabled, egui::Button::selectable(on, label)).clicked() { + let _ = crate::menus::invoke(app, &ctx, id, json!({})); + ui.close(); } - }); + } }); }); + }); } /// Glyph size of a toolbar tool button. Pro fills two thirds of the button, close to Photoshop's @@ -507,9 +535,10 @@ pub(super) fn toolbar_icon_size(box_size: f32, pro: bool) -> f32 { /// Paints a triangle on the bottom corner of an icon button that faces the canvas (bottom right, /// bottom left in a right-to-left UI) to indicate that a toolbar item has a submenu. -pub fn paint_toolbar_flyout_indicator(ui: &mut egui::Ui, tokens: &Tokens, resp: &egui::Response) { +pub fn paint_toolbar_flyout_indicator(ui: &mut egui::Ui, tokens: &Tokens, resp: &egui::Response, side: ToolbarSide) { let r = resp.rect; - let tri = if crate::direction::is_rtl() { + // The corner nearest the canvas, so the triangle faces the flyout. + let tri = if side == ToolbarSide::Right { vec![r.left_bottom() + vec2(2.0, -2.0), r.left_bottom() + vec2(6.0, -2.0), r.left_bottom() + vec2(2.0, -6.0)] } else { vec![r.right_bottom() + vec2(-2.0, -2.0), r.right_bottom() + vec2(-6.0, -2.0), r.right_bottom() + vec2(-2.0, -6.0)] diff --git a/crates/ui-egui/src/patch_cursor_badge_tests.rs b/crates/ui-egui/src/patch_cursor_badge_tests.rs new file mode 100644 index 0000000000..e9cf4b1f0b --- /dev/null +++ b/crates/ui-egui/src/patch_cursor_badge_tests.rs @@ -0,0 +1,119 @@ +//! The Patch tool's cursor shows a right-pointing arrow over the selection (#12130). + +use egui::Modifiers; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::Drag; +use crate::state::Tool; +use crate::tool_feedback::{Badge, badge, badge_glyph}; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("select.rect", json!({"x": 20, "y": 20, "width": 30, "height": 30})).unwrap(); + app +} + +const INSIDE: [f64; 2] = [30.0, 30.0]; +const OUTSIDE: [f64; 2] = [80.0, 80.0]; + +#[test] +fn arrow_over_the_selection_without_modifiers() { + let mut app = app(); + app.hover_doc = Some(INSIDE); + assert_eq!(badge(&app, Tool::Patch, Modifiers::NONE), Some(Badge::Arrow)); + assert_ne!(Badge::Arrow, Badge::Move, "a new single-arrow glyph"); + // Size 4 is the half-length h of the shaft; the barbs fall back by a = 0.6 h. + let (h, a, eps) = (4.0_f32, 2.4_f32, 1e-5_f32); + let glyph = badge_glyph(Badge::Arrow, egui::pos2(0.0, 0.0), h); + assert_eq!(glyph.len(), 3, "one shaft and two barbs"); + let near = |p: egui::Pos2, x: f32, y: f32| (p.x - x).abs() < eps && (p.y - y).abs() < eps; + assert!(near(glyph[0][0], -h, 0.0) && near(glyph[0][1], h, 0.0), "shaft through the centre: {:?}", glyph[0]); + for barb in &glyph[1..] { + assert!(near(barb[0], h, 0.0), "a barb starts at the tip: {barb:?}"); + } + let (up, down) = (glyph[1][1], glyph[2][1]); + assert!((up.x - (h - a)).abs() < eps && (down.x - (h - a)).abs() < eps, "barbs end behind the tip"); + assert!((up.y + down.y).abs() < eps && (up.y.abs() - a).abs() < eps, "barb ends mirror about the shaft: {up:?} {down:?}"); +} + +#[test] +fn the_arrow_stays_during_a_drag_started_inside() { + let mut app = app(); + app.drag = Some(Drag::new(Tool::Patch, INSIDE, vec![[INSIDE[0], INSIDE[1], 1.0]], Modifiers::NONE, false)); + app.hover_doc = Some(OUTSIDE); + assert_eq!(badge(&app, Tool::Patch, Modifiers::NONE), Some(Badge::Arrow)); +} + +#[test] +fn outside_and_with_shift_or_alt_the_badges_are_as_before() { + let mut app = app(); + app.hover_doc = Some(OUTSIDE); + assert_eq!(badge(&app, Tool::Patch, Modifiers::NONE), None); + app.hover_doc = Some(INSIDE); + assert_eq!(badge(&app, Tool::Patch, Modifiers::SHIFT), Some(Badge::Add)); + assert_eq!(badge(&app, Tool::Patch, Modifiers::ALT), Some(Badge::Subtract)); +} + +#[test] +fn a_patch_drag_started_outside_does_not_show_the_arrow_when_it_enters_the_selection() { + let mut app = app(); + app.hover_doc = Some(OUTSIDE); + let plain_outside = badge(&app, Tool::Patch, Modifiers::NONE); + app.drag = Some(Drag::new(Tool::Patch, OUTSIDE, vec![[OUTSIDE[0], OUTSIDE[1], 1.0]], Modifiers::NONE, false)); + app.hover_doc = Some(INSIDE); + assert_eq!(badge(&app, Tool::Patch, Modifiers::NONE), plain_outside); + assert_ne!(badge(&app, Tool::Patch, Modifiers::NONE), Some(Badge::Arrow)); +} + +#[test] +fn content_aware_move_has_no_arrow_even_in_a_drag_started_inside() { + let mut app = app(); + app.drag = Some(Drag::new(Tool::ContentAwareMove, INSIDE, vec![[INSIDE[0], INSIDE[1], 1.0]], Modifiers::NONE, false)); + app.hover_doc = Some(INSIDE); + assert_eq!(badge(&app, Tool::ContentAwareMove, Modifiers::NONE), None); +} + +/// The release reads the press's modifiers, so ⇧ or ⌥ pressed mid-drag changes nothing. +#[test] +fn modifiers_pressed_mid_drag_do_not_change_the_badge() { + let mut app = app(); + app.drag = Some(Drag::new(Tool::Patch, INSIDE, vec![[INSIDE[0], INSIDE[1], 1.0]], Modifiers::NONE, false)); + app.hover_doc = Some(OUTSIDE); + for m in [Modifiers::SHIFT, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT] { + assert_eq!(badge(&app, Tool::Patch, m), Some(Badge::Arrow), "{m:?}"); + } +} + +#[test] +fn a_drag_pressed_with_shift_or_alt_keeps_that_badge() { + let mut app = app(); + app.hover_doc = Some(INSIDE); + for (pressed, want) in [(Modifiers::SHIFT, Badge::Add), (Modifiers::ALT, Badge::Subtract)] { + app.drag = Some(Drag::new(Tool::Patch, INSIDE, vec![[INSIDE[0], INSIDE[1], 1.0]], pressed, false)); + assert_eq!(badge(&app, Tool::Patch, pressed), Some(want)); + assert_eq!(badge(&app, Tool::Patch, Modifiers::NONE), Some(want), "released keys mid-drag"); + } +} + +#[test] +fn shift_and_alt_together_over_the_selection_intersect() { + let mut app = app(); + app.hover_doc = Some(INSIDE); + assert_eq!(badge(&app, Tool::Patch, Modifiers::SHIFT | Modifiers::ALT), Some(Badge::Intersect)); +} + +#[test] +fn content_aware_move_and_the_curvature_pen_keep_their_cursors() { + let mut app = app(); + app.hover_doc = Some(INSIDE); + assert_eq!(badge(&app, Tool::ContentAwareMove, Modifiers::NONE), None); + // The Curvature Pen over an anchor of the active path: four arrows. + let path = json!({"subpaths": [{"closed": true, "knots": [[40, 40], [160, 40], [160, 160], [40, 160]]}]}); + app.run("path.set", json!({"name": "work", "path": path})).unwrap(); + app.ui.tool = Tool::CurvaturePen; + app.hover_doc = Some([160.0, 40.0]); + assert_eq!(badge(&app, Tool::CurvaturePen, Modifiers::NONE), Some(Badge::Move)); + assert_eq!(badge_glyph(Badge::Move, egui::pos2(0.0, 0.0), 4.0).len(), 10, "four-arrow glyph unchanged"); +} diff --git a/crates/ui-egui/src/patch_shift_constrain_tests.rs b/crates/ui-egui/src/patch_shift_constrain_tests.rs new file mode 100644 index 0000000000..590d4ed5b5 --- /dev/null +++ b/crates/ui-egui/src/patch_shift_constrain_tests.rs @@ -0,0 +1,103 @@ +//! #12129: ⇧ pressed during a Patch drag (after the press) keeps the drag horizontal or vertical. +//! Only 0 and 90 degrees snap; ⇧ at the press still adds to the selection. + +use egui::Modifiers; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// A 500 x 400 document with 100..200 square selected, the Patch tool active. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 500, "height": 400, "background": "white"})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 100, "height": 100, "mode": "replace"})).unwrap(); + app.ui.tool = Tool::Patch; + app.ui.tool_options.patch_content_aware = false; + app +} + +fn mv(app: &mut PhotocraftApp, x: f64, y: f64, m: Modifiers) { + tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, m); +} + +/// Press at 140,140 without ⇧, move past the first 60 px, then to `to` with `m` held. +fn drag_to(app: &mut PhotocraftApp, to: [f64; 2], m: Modifiers) { + tool_event(app, ToolEvent::Down { x: 140.0, y: 140.0, pressure: 1.0 }, Modifiers::NONE); + mv(app, 200.0, 145.0, Modifiers::NONE); + mv(app, to[0], to[1], m); +} + +fn patch_offsets(app: &PhotocraftApp) -> Vec { + app.session.journal.iter().filter(|(id, _)| id == "paint.patch").map(|(_, p)| p["offset"].clone()).collect() +} + +fn outline_offset(app: &mut PhotocraftApp) -> [i32; 2] { + let (start, end) = { + let d = app.drag.as_ref().unwrap(); + (d.start, crate::retouch_ui::patch_end(d, d.points.last().map_or(d.start, |p| [p[0], p[1]]))) + }; + crate::retouch_ui::patch_offset(app, start, end) +} + +#[test] +fn shift_during_the_drag_snaps_the_offset_to_the_dominant_axis() { + let mut app = app(); + drag_to(&mut app, [380.0, 170.0], Modifiers::SHIFT); + assert_eq!(crate::patch_preview::drag_offset(&mut app), Some([240, 0])); + + let mut app = self::app(); + drag_to(&mut app, [380.0, 170.0], Modifiers::NONE); + assert_eq!(crate::patch_preview::drag_offset(&mut app), Some([240, 30]), "without ⇧ the offset is free"); + + // The dominant axis can be vertical too. + let mut app = self::app(); + drag_to(&mut app, [150.0, 300.0], Modifiers::SHIFT); + assert_eq!(crate::patch_preview::drag_offset(&mut app), Some([0, 160])); +} + +#[test] +fn the_outline_the_preview_and_the_applied_patch_use_the_snapped_offset() { + let mut app = app(); + drag_to(&mut app, [380.0, 170.0], Modifiers::SHIFT); + assert_eq!(outline_offset(&mut app), [240, 0], "outline"); + assert_eq!(crate::patch_preview::drag_offset(&mut app), Some([240, 0]), "preview"); + tool_event(&mut app, ToolEvent::Up { x: 380.0, y: 170.0 }, Modifiers::SHIFT); + assert!(!app.ui.status_error, "{}", app.ui.status); + assert_eq!(patch_offsets(&app), vec![json!([240, 0])], "applied patch"); + + let mut app = self::app(); + drag_to(&mut app, [380.0, 170.0], Modifiers::NONE); + assert_eq!(outline_offset(&mut app), [240, 30]); + tool_event(&mut app, ToolEvent::Up { x: 380.0, y: 170.0 }, Modifiers::NONE); + assert_eq!(patch_offsets(&app), vec![json!([240, 30])]); +} + +#[test] +fn shift_at_mouse_down_still_adds_to_the_selection() { + let mut app = app(); + let m = Modifiers::SHIFT; + tool_event(&mut app, ToolEvent::Down { x: 140.0, y: 140.0, pressure: 1.0 }, m); + for [x, y] in [[300.0, 140.0], [340.0, 140.0], [340.0, 180.0], [300.0, 180.0]] { + mv(&mut app, x, y, m); + } + tool_event(&mut app, ToolEvent::Up { x: 300.0, y: 180.0 }, m); + assert!(patch_offsets(&app).is_empty(), "no patch was applied"); + let sel = app.session.active().unwrap().doc.selection.clone().unwrap(); + assert!(sel.sample_channel(150, 150, 0) > 0.0, "the old selection is kept"); + assert!(sel.sample_channel(320, 160, 0) > 0.0, "the lasso is added"); +} + +#[test] +fn only_horizontal_and_vertical_snap_never_forty_five_degrees() { + // A perfect diagonal still goes to one axis. + let mut app = app(); + drag_to(&mut app, [240.0, 240.0], Modifiers::SHIFT); + let off = crate::patch_preview::drag_offset(&mut app).unwrap(); + assert!(off[0] == 0 || off[1] == 0, "{off:?} is not on an axis"); + // A 160 x 120 drag is not pulled to 45 degrees (140 x 140). + let mut app = self::app(); + drag_to(&mut app, [300.0, 260.0], Modifiers::SHIFT); + assert_eq!(crate::patch_preview::drag_offset(&mut app), Some([160, 0])); +} diff --git a/crates/ui-egui/src/patch_tool_history_names_tests.rs b/crates/ui-egui/src/patch_tool_history_names_tests.rs new file mode 100644 index 0000000000..d0dc3e771d --- /dev/null +++ b/crates/ui-egui/src/patch_tool_history_names_tests.rs @@ -0,0 +1,42 @@ +//! The Patch tool's lasso is a History step named "Patch Tool" (#12117); the Lasso tool keeps "Lasso". + +use egui::Modifiers; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +fn app_with(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + app +} + +/// Drag a triangle with the active tool and return the last History step. +fn drag_lasso(app: &mut PhotocraftApp) -> Option { + tool_event(app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, Modifiers::NONE); + for (x, y) in [(200.0, 100.0), (300.0, 100.0), (300.0, 300.0)] { + tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, Modifiers::NONE); + } + tool_event(app, ToolEvent::Up { x: 200.0, y: 300.0 }, Modifiers::NONE); + assert!(app.session.active().unwrap().doc.selection.is_some()); + app.session.active().unwrap().history.entries().last().cloned() +} + +#[test] +fn the_patch_tool_lasso_is_named_for_the_tool() { + assert_eq!(drag_lasso(&mut app_with(Tool::Patch)).as_deref(), Some("Patch Tool")); + assert_eq!(drag_lasso(&mut app_with(Tool::Lasso)).as_deref(), Some("Lasso")); +} + +/// A Patch tool lasso keeps the selection icon in the History panel. +#[test] +fn the_patch_tool_step_has_the_selection_icon() { + assert_eq!(crate::panels::history_step_icon("Patch Tool"), crate::panels::history_step_icon("Lasso")); + assert_eq!(crate::panels::history_step_icon("Patch Tool"), "square-dashed"); + // Applying the patch edits pixels, so it does not take the selection icon from "Selection". + assert_ne!(crate::panels::history_step_icon("Patch Selection"), "square-dashed"); +} diff --git a/crates/ui-egui/src/pen_variants_tests.rs b/crates/ui-egui/src/pen_variants_tests.rs index aefc2bb3c7..2e73604cc9 100644 --- a/crates/ui-egui/src/pen_variants_tests.rs +++ b/crates/ui-egui/src/pen_variants_tests.rs @@ -494,3 +494,119 @@ fn the_pen_does_not_carry_on_a_work_path_hidden_by_make_selection() { assert_eq!(anchors(&saved.path), [vec![[150.0, 150.0], [200.0, 150.0], [200.0, 190.0]]], "the saved path carried on"); assert_eq!(anchors(&work_path(&app)).len(), 1, "the hidden Work Path untouched"); } + +/// #9356: in Shape mode a Pen press on an endpoint of the selected shape layer's open path carries +/// that path on, from either end, and the commit updates the same layer in one History step +/// instead of making a new shape layer. Elsewhere the press starts a new shape as before. +#[test] +fn shape_mode_carries_on_the_selected_shapes_open_path() { + let mut app = app(Tool::Pen); + app.ui.tool_options.vector_mode = "shape".into(); + let layers = |app: &PhotocraftApp| app.session.active().unwrap().doc.layers.len(); + let shape = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { + LayerContent::Shape(sh) => { + sh.path.subpaths.iter().map(|s| s.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect::>()).collect::>() + } + other => panic!("not a shape layer: {other:?}"), + } + }; + let steps = |app: &PhotocraftApp| app.session.active().unwrap().history.past_len(); + click(&mut app, 20.0, 20.0); + click(&mut app, 80.0, 20.0); + crate::vector_ui::pen_commit(&mut app, false); + let (n, before) = (layers(&app), steps(&app)); + assert!(crate::vector_ui::continues_path_at(&app, Tool::Pen, 81.0, 21.0), "the continue pointer over the endpoint"); + assert!(!crate::vector_ui::continues_path_at(&app, Tool::Pen, 50.0, 20.0), "not mid-segment"); + click(&mut app, 80.0, 20.0); + click(&mut app, 80.0, 80.0); + crate::vector_ui::pen_commit(&mut app, false); + assert_eq!(layers(&app), n, "no new shape layer"); + assert_eq!(steps(&app), before + 1, "one History step"); + assert_eq!(shape(&app), [vec![[20.0, 20.0], [80.0, 20.0], [80.0, 80.0]]]); + // From the first anchor, reversed. + click(&mut app, 20.0, 20.0); + click(&mut app, 20.0, 80.0); + crate::vector_ui::pen_commit(&mut app, false); + assert_eq!(shape(&app), [vec![[80.0, 80.0], [80.0, 20.0], [20.0, 20.0], [20.0, 80.0]]]); + // Anywhere else: a new shape layer. + click(&mut app, 150.0, 150.0); + click(&mut app, 200.0, 150.0); + crate::vector_ui::pen_commit(&mut app, false); + assert_eq!(layers(&app), n + 1); +} + +/// #9356: with a vector mask targeted, the Pen carries on the mask's open subpath in place. +#[test] +fn a_targeted_vector_mask_carries_on_its_open_path() { + let mut app = app(Tool::Pen); + let id = app.session.active().unwrap().active_layer.unwrap(); + let open = json!({"subpaths": [{"closed": false, "knots": [{"anchor": [20.0, 20.0]}, {"anchor": [80.0, 20.0]}]}]}); + app.run("layer.vectorMask.add", json!({"layer": id.0, "path": open})).unwrap(); + app.ui.vector_mask_target = true; + let mask = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + let p = &st.doc.layer(id).unwrap().vector_mask.as_ref().unwrap().path; + p.subpaths.iter().map(|s| s.knots.len()).collect::>() + }; + assert_eq!(mask(&app), [2]); + click(&mut app, 80.0, 20.0); + click(&mut app, 80.0, 80.0); + crate::vector_ui::pen_commit(&mut app, false); + assert_eq!(mask(&app), [3], "the same subpath, extended"); +} + +/// #9396 review: on a short open path whose two ends are both within reach of the pointer (as +/// when zoomed out), the press under the continue-path pointer carries the nearer end on and never +/// closes the path, which it did when the other end was its first anchor. +#[test] +fn a_press_in_reach_of_both_ends_carries_the_nearer_one_on_and_does_not_close() { + let mut app = app(Tool::Pen); + assert_eq!(app.point_zoom(), 1.0, "a 6 px reach in document pixels"); + // The ends sit beside the first segment, which Auto Add/Delete would put an anchor on. + app.ui.tool_options.pen_auto_add_delete = false; + for (x, y) in [(20.0, 20.0), (60.0, 20.0), (60.0, 40.0), (26.0, 22.0)] { + click(&mut app, x, y); + } + crate::vector_ui::pen_commit(&mut app, false); + let ends = |app: &PhotocraftApp| { + let pen = app.ui.pen.as_ref().expect("a resumed draft"); + assert!(pen.resumes.is_some(), "{pen:?}"); + pen.knots.last().map(|k| k[0]) + }; + // (24, 22): 2 px from the last anchor, 4.5 px from the first. + assert!(crate::vector_ui::continues_path_at(&app, Tool::Pen, 24.0, 22.0)); + click(&mut app, 24.0, 22.0); + assert!(!work_path(&app).subpaths[0].closed, "the press carried the path on, it did not close it"); + assert_eq!(ends(&app), Some([26.0, 22.0]), "from the nearer, last anchor"); + click(&mut app, 100.0, 100.0); + crate::vector_ui::pen_commit(&mut app, false); + let sub = &work_path(&app).subpaths[0]; + assert!(!sub.closed && sub.knots.len() == 5 && sub.knots[4].anchor.x == 100.0, "{sub:?}"); + // (21, 20): 1 px from the first anchor, 5.4 px from the last: carried on from the first. + click(&mut app, 21.0, 20.0); + assert!(!work_path(&app).subpaths[0].closed); + assert_eq!(ends(&app), Some([20.0, 20.0]), "from the nearer, first anchor"); +} + +/// #9396 review: with the ends of two open subpaths both within reach, the press carries on the +/// subpath whose end is nearest the pointer, not the first one listed. +#[test] +fn a_press_in_reach_of_two_subpaths_ends_carries_the_nearest_on() { + let mut app = app(Tool::Pen); + assert_eq!(app.point_zoom(), 1.0, "a 6 px reach in document pixels"); + app.ui.tool_options.pen_auto_add_delete = false; + click(&mut app, 20.0, 20.0); + click(&mut app, 60.0, 20.0); + crate::vector_ui::pen_commit(&mut app, false); + click(&mut app, 100.0, 100.0); + click(&mut app, 64.0, 22.0); + crate::vector_ui::pen_commit(&mut app, false); + assert_eq!(work_path(&app).subpaths.len(), 2, "two open subpaths"); + // (63, 21): 3.2 px from the first subpath's last anchor, 1.4 px from the second's. + click(&mut app, 63.0, 21.0); + let pen = app.ui.pen.as_ref().expect("a resumed draft"); + assert_eq!(pen.resumes.as_ref().map(|r| r.index), Some(1), "{pen:?}"); + assert_eq!(pen.knots.last().map(|k| k[0]), Some([64.0, 22.0]), "from the second subpath's nearer end"); +} diff --git a/crates/ui-egui/src/pencil_auto_erase_tooltip_tests.rs b/crates/ui-egui/src/pencil_auto_erase_tooltip_tests.rs new file mode 100644 index 0000000000..7ae125d24a --- /dev/null +++ b/crates/ui-egui/src/pencil_auto_erase_tooltip_tests.rs @@ -0,0 +1,34 @@ +//! #11968: hovering the Pencil's Auto Erase checkbox shows "Draws background color over +//! foreground colors", in the Pro and the other themes. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; +use crate::theme::ThemeKind; + +const TIP: &str = "Draws background color over foreground colors"; + +fn bar(theme: ThemeKind) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = Tool::Pencil; + let mut h = Harness::builder().with_size(vec2(1600.0, 300.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, theme); + h.run_steps(4); + h +} + +#[test] +fn auto_erase_has_the_reference_tooltip() { + for theme in [ThemeKind::ProMedium, ThemeKind::Classic] { + let mut h = bar(theme); + // Hovering the checkbox's label shows it. + h.get_by_label("Auto Erase").hover(); + h.run_steps(60); + assert!(h.query_by_label(TIP).is_some(), "{theme:?}: no tooltip on hover"); + } +} diff --git a/crates/ui-egui/src/pencil_pressure_toggles_tests.rs b/crates/ui-egui/src/pencil_pressure_toggles_tests.rs new file mode 100644 index 0000000000..4a6a2031e4 --- /dev/null +++ b/crates/ui-egui/src/pencil_pressure_toggles_tests.rs @@ -0,0 +1,177 @@ +//! #11962: the Pencil's options bar gets the two pressure toggles, editing the Pencil's own +//! brush; the Brush keeps its own. Pro themes show the icon toggles, the others the labelled +//! switches, both with the reference tooltips. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable, by}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; +use crate::theme::ThemeKind; + +fn bar(theme: ThemeKind) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap(); + app.ui.tool = Tool::Pencil; + let mut h = Harness::builder().with_size(vec2(1600.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, theme); + h.run_steps(4); + h +} + +fn description(h: &Harness<'static, PhotocraftApp>, label: &str) -> Option { + h.query_all_by_label(label).next().and_then(|n| n.accesskit_node().description().map(|d| d.to_string())) +} + +const PRO: [(&str, &str); 2] = [ + ("Always use pressure for opacity", "Always use Pressure for Opacity. When off, Brush Preset controls pressure"), + ("Always use pressure for size", "Always use Pressure for Size. When off, Brush Preset controls pressure"), +]; + +const CLASSIC: [(&str, &str); 2] = [ + ("Pressure for Size", "Always use Pressure for Size. When off, Brush Preset controls pressure"), + ("Pressure for Opacity", "Always use Pressure for Opacity. When off, Brush Preset controls pressure"), +]; + +#[test] +fn the_pro_bar_shows_both_toggles_with_the_reference_tooltips() { + let h = bar(ThemeKind::ProMedium); + for (label, tip) in PRO { + assert_eq!(h.query_all_by_label(label).count(), 1, "{label} exists once"); + assert_eq!(description(&h, label).as_deref(), Some(tip), "{label} tooltip"); + } +} + +#[test] +fn the_pro_toggles_edit_the_pencils_own_flags_and_brush_get_sees_them() { + let mut h = bar(ThemeKind::ProMedium); + let flags = |h: &Harness<'static, PhotocraftApp>| (h.state().session.tools.brush.pressure_opacity, h.state().session.tools.brush.pressure_size); + assert_eq!(flags(&h), (false, false), "both off on a fresh Pencil"); + h.get_by_label("Always use pressure for opacity").click(); + h.run_steps(2); + h.get_by_label("Always use pressure for size").click(); + h.run_steps(2); + assert_eq!(flags(&h), (true, true)); + let got = h.state_mut().run("brush.get", json!({})).unwrap(); + assert_eq!(got["pressureOpacity"], json!(true), "brush.get reads the Pencil's flag"); + assert_eq!(got["pressureSize"], json!(true)); +} + +#[test] +fn the_brush_keeps_its_own_pressure_flags() { + let mut h = bar(ThemeKind::ProMedium); + let flags = |h: &Harness<'static, PhotocraftApp>| (h.state().session.tools.brush.pressure_opacity, h.state().session.tools.brush.pressure_size); + let toggle = |h: &mut Harness<'static, PhotocraftApp>, label: &str| { + h.get_by_label(label).click(); + h.run_steps(2); + }; + + // Give the Brush its own brush first, so the Pencil's later toggles cannot be "inherited" on + // the first switch and hide a leak. + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(4); + h.state_mut().session.tools.brush.pressure_opacity = false; + h.state_mut().session.tools.brush.pressure_size = false; + h.run_steps(2); + + h.state_mut().ui.tool = Tool::Pencil; + h.run_steps(4); + toggle(&mut h, "Always use pressure for opacity"); + toggle(&mut h, "Always use pressure for size"); + assert_eq!(flags(&h), (true, true), "the Pencil's flags are on"); + + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(4); + assert_eq!(flags(&h), (false, false), "the Pencil's toggles did not change the Brush"); + h.state_mut().ui.tool = Tool::Pencil; + h.run_steps(4); + assert_eq!(flags(&h), (true, true), "the Pencil's flags came back"); + + // The mirror: the Brush on, the Pencil off, so a reset to one value cannot pass. + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(4); + h.state_mut().session.tools.brush.pressure_opacity = true; + h.state_mut().session.tools.brush.pressure_size = true; + h.run_steps(2); + h.state_mut().ui.tool = Tool::Pencil; + h.run_steps(4); + toggle(&mut h, "Always use pressure for opacity"); + toggle(&mut h, "Always use pressure for size"); + assert_eq!(flags(&h), (false, false), "the Pencil is off"); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(4); + assert_eq!(flags(&h), (true, true), "the Brush stayed on"); + h.state_mut().ui.tool = Tool::Pencil; + h.run_steps(4); + assert_eq!(flags(&h), (false, false), "the Pencil stayed off"); + + // A mixed setting: opacity on, size off, across a switch and back. + toggle(&mut h, "Always use pressure for opacity"); + assert_eq!(flags(&h), (true, false), "mixed: opacity on, size off"); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(4); + assert_eq!(flags(&h), (true, true), "the Brush still has its own pair"); + h.state_mut().ui.tool = Tool::Pencil; + h.run_steps(4); + assert_eq!(flags(&h), (true, false), "the mixed pair came back unchanged"); + // And the bar draws that pair, not just stores it. + let on = |h: &Harness<'static, PhotocraftApp>, label: &str| h.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True); + assert!(on(&h, "Always use pressure for opacity"), "the opacity toggle reads as on"); + assert!(!on(&h, "Always use pressure for size"), "the size toggle reads as off"); +} + +#[test] +fn the_other_themes_show_the_labelled_toggles() { + let mut h = bar(ThemeKind::Classic); + // The switches are unnamed nodes: their tooltips are the descriptions in the bar. + let tips: Vec = + h.query_all(by().predicate(|n| n.description().is_some())).filter_map(|n| n.accesskit_node().description().map(|d| d.to_string())).collect(); + for (label, tip) in CLASSIC { + assert_eq!(h.query_all_by_label(label).count(), 1, "{label} exists once"); + assert!(tips.iter().any(|d| d == tip), "{label} tooltip: {tips:?}"); + } + for (label, tip, expect) in [("Pressure for Size", CLASSIC[0].1, true), ("Pressure for Opacity", CLASSIC[1].1, true)] { + let at = h + .query_all(by().predicate(move |n| n.description().map(|d| d == tip).unwrap_or(false))) + .next() + .unwrap_or_else(|| panic!("no switch for {label}")) + .rect() + .center(); + h.hover_at(at); + h.run(); + h.drag_at(at); + h.run(); + h.drop_at(at); + h.run_steps(2); + let flag = if label.ends_with("Size") { h.state().session.tools.brush.pressure_size } else { h.state().session.tools.brush.pressure_opacity }; + assert_eq!(flag, expect, "{label} toggles the Pencil's flag"); + } +} + +/// Painted width at column `x` on the active layer, through the stroke's row band. +fn width(app: &PhotocraftApp, x: i32, y: i32) -> usize { + let st = app.session.active().expect("a document"); + let layer = st.active_layer.expect("an active layer"); + let s = st.doc.layer(layer).and_then(|l| l.surface()).expect("a raster layer"); + (y - 20..=y + 20).filter(|yy| s.rgba(x, *yy)[3] > 0.5).count() +} + +#[test] +fn pressure_for_size_narrows_a_low_pressure_pencil_stroke() { + let mut h = bar(ThemeKind::ProMedium); + let app = h.state_mut(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 13.0, "pressureSize": true, "smoothing": {"amount": 0.0}}})).unwrap(); + app.run("paint.pencil", json!({"points": [[20.0, 50.0, 0.2], [30.0, 50.0, 0.2], [60.0, 50.0, 1.0]]})).unwrap(); + let (low, high) = (width(app, 22, 50), width(app, 58, 50)); + assert!(low < high, "pressure for size on: low-pressure {low} px, high-pressure {high} px"); + assert!((2..=4).contains(&low), "pressure for size on: the 0.2 stroke is about 3 px, got {low}"); + + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"pressureSize": false}})).unwrap(); + app.run("paint.pencil", json!({"points": [[20.0, 50.0, 0.2], [30.0, 50.0, 0.2], [60.0, 50.0, 1.0]]})).unwrap(); + let (low, high) = (width(app, 22, 50), width(app, 58, 50)); + assert_eq!((low, high), (13, 13), "pressure for size off: every dab is 13 px"); +} diff --git a/crates/ui-egui/src/pencil_shift_digit_opacity_tests.rs b/crates/ui-egui/src/pencil_shift_digit_opacity_tests.rs new file mode 100644 index 0000000000..060133d612 --- /dev/null +++ b/crates/ui-egui/src/pencil_shift_digit_opacity_tests.rs @@ -0,0 +1,81 @@ +//! #11967: the Pencil has no Flow, so ⇧ plus a digit sets its Opacity as a plain digit does +//! (⇧3 = 30%, ⇧0 = 100%, two quick ⇧ digits an exact value). The Brush's ⇧ digits still set Flow, +//! swapped with Opacity while airbrush build-up is on. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::opacity_keys::press; +use crate::state::Tool; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = tool; + app +} + +/// The brush settings' (opacity, flow) in percent. +fn brush(app: &PhotocraftApp) -> (f32, f32) { + let b = &app.session.tools.brush; + ((b.opacity * 100.0).round(), (b.flow * 100.0).round()) +} + +#[test] +fn shift_digits_set_the_pencils_opacity() { + let mut a = app(Tool::Pencil); + let flow = brush(&a).1; + press(&mut a, 3, true, 0.0); + assert_eq!(brush(&a), (30.0, flow), "⇧3"); + press(&mut a, 0, true, 5000.0); + assert_eq!(brush(&a), (100.0, flow), "⇧0"); + for d in 1..=9u8 { + press(&mut a, d, true, 10000.0 * f64::from(d)); + assert_eq!(brush(&a), (f32::from(d) * 10.0, flow), "⇧{d}"); + } +} + +#[test] +fn two_quick_shift_digits_set_an_exact_opacity() { + let mut a = app(Tool::Pencil); + press(&mut a, 4, true, 0.0); + press(&mut a, 5, true, 300.0); + assert_eq!(brush(&a).0, 45.0); + press(&mut a, 0, true, 5000.0); + press(&mut a, 7, true, 5300.0); + assert_eq!(brush(&a).0, 7.0); + // As a plain `00`, which is 100 % for the Pencil (#11812). Joined, typed slowly or with the + // second press ignored, ⇧0 ⇧0 ends at 100 % either way. + press(&mut a, 0, true, 10000.0); + press(&mut a, 0, true, 10300.0); + assert_eq!(brush(&a).0, 100.0); +} + +/// No digit, plain or ⇧, ever changes the Flow while the Pencil is active, build-up on or off. +#[test] +fn the_pencils_flow_stays_untouched() { + for build_up in [false, true] { + let mut a = app(Tool::Pencil); + a.run("tools.setBrush", json!({"brush": {"flow": 0.42}})).unwrap(); + a.session.tools.brush.build_up = build_up; + for (i, (d, shift)) in [(3, true), (6, false), (0, true), (8, false)].into_iter().enumerate() { + press(&mut a, d, shift, 10000.0 * i as f64); + assert_eq!(brush(&a).1, 42.0, "build-up {build_up}, digit {d}, ⇧ {shift}"); + assert_eq!(a.session.tools.brush.build_up, build_up, "the case under test holds"); + } + assert_eq!(brush(&a).0, 80.0, "build-up {build_up}: the last digit set the Opacity"); + } +} + +#[test] +fn the_brushs_shift_digits_still_set_flow() { + let mut a = app(Tool::Brush); + press(&mut a, 3, true, 0.0); + assert_eq!(brush(&a), (100.0, 30.0), "⇧3 is Flow"); + // With airbrush build-up the roles swap: ⇧ digits set Opacity, plain ones Flow. + a.session.tools.brush.build_up = true; + press(&mut a, 6, true, 5000.0); + press(&mut a, 2, false, 10000.0); + assert_eq!(brush(&a), (60.0, 20.0)); +} diff --git a/crates/ui-egui/src/preferences_submenu_tests.rs b/crates/ui-egui/src/preferences_submenu_tests.rs index 65b54dc4eb..7050d385c0 100644 --- a/crates/ui-egui/src/preferences_submenu_tests.rs +++ b/crates/ui-egui/src/preferences_submenu_tests.rs @@ -1,4 +1,4 @@ -//! #11398: Edit › Preferences says "Plugins…" and "Camera Raw…" and has the reference +//! #11398: Edit › Preferences says "Plugins…" and "RAW Defaults…" and has the reference //! application's two separators (after the first entry and before Camera Raw…). use crate::menu_catalog::CATALOG; @@ -33,7 +33,7 @@ fn preferences_submenu_reads_in_the_reference_order_with_two_separators() { "Type…", "Enhanced Controls…", "---", - "Camera Raw…", + "RAW Defaults…", ] ); } @@ -76,12 +76,12 @@ fn engine_labels_match_the_catalogue_for_the_renamed_rows() { assert_eq!(engine, catalogue, "{id}"); } assert_eq!(photocraft_engine::commands::find("edit.preferences.plugIns").unwrap().label, "Plugins…"); - assert_eq!(photocraft_engine::commands::find("edit.preferences.rawDefaults").unwrap().label, "Camera Raw…"); + assert_eq!(photocraft_engine::commands::find("edit.preferences.rawDefaults").unwrap().label, "RAW Defaults…"); } #[test] fn preferences_dialog_page_names_follow_the_menu() { let title = |key: &str| photocraft_engine::prefs::SECTIONS.iter().find(|(k, _)| *k == key).map(|(_, t)| *t); assert_eq!(title("plugIns"), Some("Plugins")); - assert_eq!(title("rawDefaults"), Some("Camera Raw Defaults")); + assert_eq!(title("rawDefaults"), Some("RAW Defaults")); } diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index 7064c8a286..5865040256 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -1019,15 +1019,15 @@ fn brush_picker_view_survives_a_restart() { let (mut app2, _) = app_with_saved(Some(saved)); tick(&mut app2, &ctx); assert!(!app2.ui.brush_picker_list.show_stroke); - assert!(app2.ui.brush_picker_list.show_name && app2.ui.brush_picker_list.show_tip); + assert!(app2.ui.brush_picker_list.show_name && !app2.ui.brush_picker_list.show_tip); assert!((app2.ui.brush_picker_list.scale - 0.4).abs() < 1e-6); - // A hand-edited file: the scale is clamped to the slider's range and the last part comes - // back on — an empty card would show no brush at all. + // A hand-edited file: the scale is clamped to the slider's range and the + // parts come back as they start — an empty card would show no brush at all. let bad = json!({"brushPicker": {"showName": false, "showStroke": false, "showTip": false, "scale": 9.0}}).to_string(); let (mut app3, _) = app_with_saved(Some(bad)); tick(&mut app3, &ctx); assert_eq!(app3.ui.brush_picker_list.scale, *crate::brush_picker::SCALE_RANGE.end()); - assert!(app3.ui.brush_picker_list.show_name && app3.ui.brush_picker_list.show_stroke && app3.ui.brush_picker_list.show_tip); + assert!(app3.ui.brush_picker_list.show_name && app3.ui.brush_picker_list.show_stroke && !app3.ui.brush_picker_list.show_tip); } #[test] diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 02c18313f5..d09d91e9d5 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -569,6 +569,7 @@ fn profile_cancel_cancels_whole_queue_including_memory_prompts() { order: None, question: Some(json!({"missing": false, "working": "sRGB", "embedded": "Adobe RGB"})), policy_applied: false, + smart_object: false, }, ); @@ -600,6 +601,7 @@ fn mixed_prompts_follow_arrival_order_fifo() { order: None, question: None, policy_applied: false, + smart_object: false, }, ); @@ -974,3 +976,34 @@ fn inline_drop_slot_survives_the_memory_prompt() { }); }); } + +/// A damaged PSD opened as a smart object, once confirmed, is admitted as one: the history says +/// "Open As Smart Object" and two same-stem files get distinct names (#12212 review). +#[test] +fn confirmed_damaged_smart_object_opens_are_admitted_as_smart_objects_with_distinct_names() { + let mut app = app(); + let bytes = recovery_psd::make_psd(true); + let dir = std::env::temp_dir().join(format!("photocraft-damaged-so-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut paths = Vec::new(); + for sub in ["a", "b"] { + std::fs::create_dir_all(dir.join(sub)).unwrap(); + let path = dir.join(sub).join("dmg.psd"); + std::fs::write(&path, &bytes).unwrap(); + paths.push(path.to_string_lossy().into_owned()); + } + for path in &paths { + crate::jobs_ui::start_open_as_smart_object(&mut app, path, None).unwrap(); + } + assert!(app.session.documents().is_empty()); + for _ in 0..2 { + let id = damage_dialog(&mut app); + assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": id}))["ok"], true); + } + let names: Vec<_> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect(); + assert_eq!(names, ["dmg-1", "dmg-2"]); + for st in app.session.documents() { + assert_eq!(st.history.entries(), ["Open As Smart Object"]); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/rasterize_prompt_text_tests.rs b/crates/ui-egui/src/rasterize_prompt_text_tests.rs new file mode 100644 index 0000000000..77a5da88bc --- /dev/null +++ b/crates/ui-egui/src/rasterize_prompt_text_tests.rs @@ -0,0 +1,39 @@ +//! #11899: the rasterize prompt for a smart object uses the reference application's wording; +//! the type, shape and fill prompts are unchanged, and the catalogs that translated the old text +//! translate the new one. + +use super::*; +use crate::i18n::{Lang, tr}; + +const OLD: &str = "This Smart Object must be rasterized before proceeding. Its contents will no longer be editable. Rasterize the Smart Object?"; + +#[test] +fn the_four_prompts_read_as_measured() { + assert_eq!( + Kind::SmartObject.message(), + "This smart object must be rasterized before proceeding. Edit Contents will no longer be available. Rasterize the smart object?" + ); + assert_eq!(Kind::Type.message(), "This type layer must be rasterized before proceeding. Its text will no longer be editable. Rasterize the type?"); + assert_eq!(Kind::Shape.message(), "This shape layer must be rasterized before proceeding. It will no longer be editable as a shape. Rasterize the shape?"); + assert_eq!(Kind::Fill.message(), "This fill layer must be rasterized before proceeding. Its fill content will no longer be editable. Rasterize the layer?"); + assert!(!Kind::SmartObject.message().contains(" "), "single spaces between sentences"); +} + +#[test] +fn catalogs_that_had_a_translation_keep_one() { + let new = Kind::SmartObject.message(); + let fr = Lang::from_code("fr").expect("French"); + assert_ne!(tr(fr, new), new, "French still translates the prompt"); + // A language without an entry falls back to English. + let de = Lang::from_code("de").expect("German"); + assert_eq!(tr(de, new), new); + // No catalog keeps the old key. + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/i18n"); + for entry in std::fs::read_dir(&dir).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_some_and(|e| e == "tsv") { + let text = std::fs::read_to_string(&path).unwrap(); + assert!(!text.contains(OLD), "{} still has the old key", path.display()); + } + } +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index e869f3f7e0..ffc33bb94c 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -429,6 +429,10 @@ pub type PenEndFn = Box Option + Send + Sync>; /// whether the app window is focused (to re-assert WinTab overlap priority on activation). pub type TabletPollFn = Box; +/// What the last self-update came to: `Ok` with the version it installed, `Err` with the reason it +/// could not be installed, `None` when there is nothing to report ([`Services::last_update`]). +pub type LastUpdateFn = fn() -> Option>; + /// Platform services injected by the app binary (file dialogs, codecs), keeping this crate free of /// I/O dependencies. #[derive(Default)] @@ -486,6 +490,9 @@ pub struct Services { pub alert: Option, /// Starts a background check for published releases (desktop, outside Flatpak). pub check_updates: Option, + /// What the last self-update came to, read once at the first frame: `Ok` with the version it + /// installed, `Err` with the reason it could not be installed (desktop). + pub last_update: Option, /// Files delivered asynchronously (web drag-and-drop): drained every frame and opened as /// documents. pub inbox: Option, diff --git a/crates/ui-egui/src/smart_filter_rows_tests.rs b/crates/ui-egui/src/smart_filter_rows_tests.rs index 722fc58f60..1d5daf2950 100644 --- a/crates/ui-egui/src/smart_filter_rows_tests.rs +++ b/crates/ui-egui/src/smart_filter_rows_tests.rs @@ -137,7 +137,7 @@ fn a_camera_raw_filter_copies_and_its_copy_opens_on_the_target() { h.state_mut().run("layer.select", json!({"layer": a})).unwrap(); h.state_mut().run("filter.cameraRaw", json!({"exposure": 1.0, "contrast": 20})).unwrap(); h.run_steps(4); - let (from, to) = (at(&h, "Camera Raw Filter"), at(&h, "Smart B")); + let (from, to) = (at(&h, "RAW Develop Filter"), at(&h, "Smart B")); drag(&mut h, from, to, Modifiers::ALT); let raw = |h: &egui_kittest::Harness<'static, PhotocraftApp>, id: u64| match &h.state().session.active().unwrap().doc.layer(LayerId(id)).unwrap().content { LayerContent::Smart(sm) => sm.smart_filters.iter().find(|f| f.command == "filter.cameraRaw").map(|f| f.params.clone()), @@ -147,7 +147,7 @@ fn a_camera_raw_filter_copies_and_its_copy_opens_on_the_target() { assert_eq!(raw(&h, b).unwrap()["exposure"], 1.0); // B is above A in the panel, so its copy is the upper of the two Camera Raw rows. let copy = h - .query_all_by_label("Camera Raw Filter") + .query_all_by_label("RAW Develop Filter") .filter(|n| n.accesskit_node().role() == Role::Button) .map(|n| n.rect().center()) .min_by(|p, q| p.y.total_cmp(&q.y)) @@ -160,7 +160,7 @@ fn a_camera_raw_filter_copies_and_its_copy_opens_on_the_target() { h.run_steps(1); } h.run_steps(3); - let dialog = h.state().camera_raw.as_ref().expect("Camera Raw opened"); + let dialog = h.state().camera_raw.as_ref().expect("RAW Develop opened"); assert_eq!(dialog.layer, LayerId(b)); } diff --git a/crates/ui-egui/src/smoothing_options_greyed_tests.rs b/crates/ui-egui/src/smoothing_options_greyed_tests.rs new file mode 100644 index 0000000000..06cd6d12de --- /dev/null +++ b/crates/ui-egui/src/smoothing_options_greyed_tests.rs @@ -0,0 +1,142 @@ +//! #11939: at Smoothing 0 % the gear's four Smoothing Options are greyed and can't be toggled, but +//! keep their values; above 0 % they work again. For the Brush and the Eraser, the tools with this +//! gear. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +const OPTIONS: [&str; 4] = ["Pulled String Mode", "Stroke Catch-up", "Catch-up on Stroke End", "Adjust for Zoom"]; + +fn bar(tool: Tool, smoothing: f32) -> Harness<'static, PhotocraftApp> { + bar_with(tool, smoothing, None) +} + +/// [`bar`] with the four options set to `options` (in [`OPTIONS`] order) before the first frame. +fn bar_with(tool: Tool, smoothing: f32, options: Option<[bool; 4]>) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + crate::paint_mouse::sync_tool_brush(&mut app); + let s = &mut app.session.tools.brush.smoothing; + s.amount = smoothing; + if let Some([a, b, c, d]) = options { + (s.pulled_string, s.catch_up, s.catch_up_on_end, s.adjust_for_zoom) = (a, b, c, d); + } + let mut h = Harness::builder().with_size(vec2(1800.0, 400.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h.get_by_label("Set additional smoothing options").click(); + h.run_steps(3); + h +} + +fn checkbox<'a>(h: &'a Harness<'static, PhotocraftApp>, label: &str) -> egui_kittest::Node<'a> { + h.query_all_by_role(Role::CheckBox).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("{label}")) +} + +fn values(h: &Harness<'static, PhotocraftApp>) -> [bool; 4] { + let s = &h.state().session.tools.brush.smoothing; + [s.pulled_string, s.catch_up, s.catch_up_on_end, s.adjust_for_zoom] +} + +#[test] +fn at_zero_the_four_are_greyed_and_keep_their_values() { + for tool in [Tool::Brush, Tool::Eraser] { + let mut h = bar(tool, 0.0); + let before = values(&h); + for label in OPTIONS { + assert!(checkbox(&h, label).accesskit_node().is_disabled(), "{tool:?}: {label} greyed at 0 %"); + } + for label in OPTIONS { + checkbox(&h, label).click(); + h.run_steps(2); + } + assert_eq!(values(&h), before, "{tool:?}: clicks change nothing at 0 %"); + } +} + +#[test] +fn above_zero_they_work_again() { + for tool in [Tool::Brush, Tool::Eraser] { + let mut h = bar(tool, 0.1); + for label in OPTIONS { + assert!(!checkbox(&h, label).accesskit_node().is_disabled(), "{tool:?}: {label} enabled"); + } + let before = values(&h); + checkbox(&h, "Pulled String Mode").click(); + h.run_steps(2); + assert_ne!(values(&h)[0], before[0], "{tool:?}: Pulled String Mode toggles"); + } +} + +#[test] +fn a_smoothing_that_shows_as_zero_greys_them_too() { + // 0.4 % (from a preset or a script) reads 0 % in the field, so the four follow the field. + for tool in [Tool::Brush, Tool::Eraser] { + let h = bar(tool, 0.004); + for label in OPTIONS { + assert!(checkbox(&h, label).accesskit_node().is_disabled(), "{tool:?}: {label} greyed at a displayed 0 %"); + } + } +} + +/// The opposite of each option's default (Pulled String off, Stroke Catch-up on, Catch-up on +/// Stroke End off, Adjust for Zoom on). +const SET: [bool; 4] = [true, false, true, false]; + +/// Types `text` into the options bar's Smoothing field, then Tabs out of it. +fn type_smoothing(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton) + .find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == "Smoothing")) + .expect("the Smoothing field") + .click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +#[test] +fn a_smoothing_that_shows_as_one_enables_them() { + // 0.9 % reads 1 % in the field, so the four are on. + for tool in [Tool::Brush, Tool::Eraser] { + let h = bar(tool, 0.009); + for label in OPTIONS { + assert!(!checkbox(&h, label).accesskit_node().is_disabled(), "{tool:?}: {label} enabled at a displayed 1 %"); + } + } +} + +#[test] +fn smoothing_to_zero_and_back_keeps_the_four_values() { + for tool in [Tool::Brush, Tool::Eraser] { + let mut h = bar_with(tool, 0.1, Some(SET)); + type_smoothing(&mut h, "0"); + assert_eq!(h.state().session.tools.brush.smoothing.amount, 0.0, "{tool:?}: Smoothing 0 %"); + assert_eq!(values(&h), SET, "{tool:?}: kept at 0 %"); + type_smoothing(&mut h, "10"); + assert_eq!(values(&h), SET, "{tool:?}: kept back above 0 %"); + } +} + +#[test] +fn at_zero_each_checkbox_shows_its_value() { + use egui::accesskit::Toggled; + for tool in [Tool::Brush, Tool::Eraser] { + for set in [SET, SET.map(|v| !v)] { + let h = bar_with(tool, 0.0, Some(set)); + for (label, on) in OPTIONS.into_iter().zip(set) { + let shown = checkbox(&h, label).accesskit_node().toggled(); + assert_eq!(shown, Some(if on { Toggled::True } else { Toggled::False }), "{tool:?}: {label} shows {on} at 0 %"); + } + } + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 5b79331819..063e14ae2a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -24,6 +24,45 @@ pub use transform::{ BoxResize, CamTransform, ContentAwareOptions, Extras, MadeLayer, TextEdit, TransformMode, TransformSession, TypeInsertionStyle, TypeTransform, }; +/// Which side of the canvas holds the tool palette. `Start` follows the UI direction; the +/// physical sides pin it so the palette can sit beside the right-hand dock. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ToolbarSide { + /// The leading edge of the interface direction: left in LTR, right in RTL. + #[default] + Start, + /// The window's left edge in every direction. + Left, + /// The window's right edge in every direction. + Right, +} + +/// Reads a [`ToolbarSide`], falling back to the default for any value it does not name. +fn toolbar_side_or_default<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let value = serde_json::Value::deserialize(d)?; + Ok(serde_json::from_value(value).unwrap_or_default()) +} + +impl ToolbarSide { + /// Resolves `Start` against the interface direction; physical sides are returned unchanged. + pub fn resolve(self) -> Self { + match self { + Self::Start if crate::direction::is_rtl() => Self::Right, + Self::Start => Self::Left, + side => side, + } + } + + /// The opposite physical side. + pub fn other(self) -> Self { + match self.resolve() { + Self::Right => Self::Left, + _ => Self::Right, + } + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Panels { pub layers: bool, @@ -46,6 +85,10 @@ pub struct Panels { /// The toolbar's header chevron: two columns even when one fits (#1197). #[serde(default)] pub toolbar_double: bool, + /// Physical side of the tool palette. `Start` mirrors with the reading direction. An unknown + /// or malformed value reads as `Start`, so it never discards the other panel flags. + #[serde(default, deserialize_with = "toolbar_side_or_default")] + pub toolbar_side: ToolbarSide, /// The right-hand panel dock. ⇧Tab hides and shows it, as in Photoshop (#1313). #[serde(default = "yes")] pub dock: bool, @@ -105,6 +148,7 @@ impl Default for Panels { brushes: false, character: false, toolbar_double: false, + toolbar_side: ToolbarSide::Start, dock: true, hidden_by_tab: None, full_screen_chrome: false, @@ -342,6 +386,10 @@ pub struct UiState { /// Selection-tool context menu opened by a plain canvas right-click. #[serde(default)] pub canvas_tool_menu: Option, + /// An outside press dismissed the canvas tool menu; suppress the corresponding + /// release click from triggering a tool action. + #[serde(default)] + pub canvas_tool_menu_dismissed: bool, /// The guide a Move-tool click selected (`guide_select`): drawn blue, Delete removes it. #[serde(default)] pub selected_guide: Option, @@ -595,6 +643,7 @@ impl Default for UiState { color_hud: None, layer_menu: None, canvas_tool_menu: None, + canvas_tool_menu_dismissed: false, selected_guide: None, brush_tool: Tool::Brush, tool_brushes: Vec::new(), @@ -726,6 +775,46 @@ impl UiState { mod tests { use super::*; + /// `toolbar_side` defaults to `Start`, serializes as a string and reads old prefs without it. + #[test] + fn toolbar_side_defaults_to_start_and_round_trips() { + assert_eq!(ToolbarSide::default(), ToolbarSide::Start); + assert_eq!(Panels::default().toolbar_side, ToolbarSide::Start); + let value = serde_json::to_value(Panels::default()).unwrap(); + assert_eq!(value["toolbar_side"], "start"); + assert_eq!(serde_json::from_value::(value).unwrap(), Panels::default()); + + let right = Panels { toolbar_side: ToolbarSide::Right, ..Default::default() }; + let value = serde_json::to_value(&right).unwrap(); + assert_eq!(value["toolbar_side"], "right"); + assert_eq!(serde_json::from_value::(value).unwrap(), right); + + let mut old = serde_json::to_value(Panels::default()).unwrap(); + old.as_object_mut().unwrap().remove("toolbar_side"); + assert_eq!(serde_json::from_value::(old).unwrap().toolbar_side, ToolbarSide::Start); + + assert_eq!(ToolbarSide::Left.other(), ToolbarSide::Right); + assert_eq!(ToolbarSide::Right.other(), ToolbarSide::Left); + } + + /// An unknown or malformed `toolbar_side` reads as `Start` and keeps every other panel flag. + #[test] + fn unknown_toolbar_side_falls_back_without_dropping_panels() { + let saved = Panels { layers: false, toolbar_double: true, toolbar_side: ToolbarSide::Left, ..Default::default() }; + for bad in + [serde_json::json!("diagonal"), serde_json::json!(5), serde_json::json!(null), serde_json::json!("RIGHT"), serde_json::json!({"side": "left"})] + { + let mut value = serde_json::to_value(&saved).unwrap(); + value["toolbar_side"] = bad.clone(); + let read = serde_json::from_value::(value).unwrap_or_else(|e| panic!("{bad} must not fail the panels: {e}")); + assert_eq!(read, Panels { toolbar_side: ToolbarSide::Start, ..saved.clone() }, "{bad}"); + } + for side in [ToolbarSide::Start, ToolbarSide::Left, ToolbarSide::Right] { + let panels = Panels { toolbar_side: side, ..saved.clone() }; + assert_eq!(serde_json::from_value::(serde_json::to_value(&panels).unwrap()).unwrap(), panels); + } + } + #[test] fn sample_all_layers_is_per_tool_and_old_prefs_load() { // The single shared flag of older preferences is dropped: every tool starts off (#5524). diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index e5db1af422..87f8207dc6 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -74,7 +74,9 @@ pub struct ToolOptions { pub cam_mode: String, pub cam_structure: f32, pub cam_color: f32, - /// Content-Aware Move: Transform On Drop (a transform box on the dropped patch). + /// Content-Aware Move: Transform On Drop (a transform box on the dropped patch). On by + /// default (#12185); a saved `false` stays off. + #[serde(default = "yes")] pub cam_transform_on_drop: bool, /// Dodge/Burn: shadows | midtones | highlights, exposure %, protect tones. pub tone_range: String, @@ -226,6 +228,9 @@ pub struct ToolOptions { pub bg_limits: String, pub bg_tolerance: f32, pub bg_protect_fg: bool, + /// The Background Eraser popup's "Tolerance:" pen control (#11910): `off`, `penPressure` (the + /// reference's default) or `stylusWheel`. + pub bg_tolerance_control: String, /// Color Replacement: mode (hue | saturation | color | luminosity), sampling (continuous | /// once | backgroundSwatch), limits (discontiguous | contiguous | findEdges), tolerance % and /// anti-alias, as `paint.colorReplacement` takes them. @@ -237,6 +242,10 @@ pub struct ToolOptions { /// Zoom tool › Scrubby Zoom: dragging left/right zooms continuously (else a zoom rectangle). #[serde(default = "yes")] pub zoom_scrubby: bool, + /// Hand tool › Scroll All Windows: a Hand drag pans every shown document view, not only the + /// one dragged in (`scroll_all_windows.rs`). Shift held while dragging does the same. + #[serde(default)] + pub hand_scroll_all: bool, /// Pencil › Auto Erase: a stroke that starts on the foreground colour paints the background colour. #[serde(default)] pub pencil_auto_erase: bool, @@ -251,6 +260,9 @@ pub struct ToolOptions { /// `paint.pencil`), as in Photoshop's options bar (#2662). #[serde(default = "default_eraser_mode")] pub eraser_mode: String, + /// Mixer Brush › Useful mixer brush combinations: the entry last picked, an index into + /// `brush_controls::MIXER_COMBINATIONS` (0 = Custom, #11946). + pub mixer_combination: usize, /// Magnetic Lasso: detection width (px, 1..256), edge contrast (%, 1..100), how often it /// fastens points by itself (0..100), and whether pen pressure narrows the width. pub magnetic_width: f32, @@ -459,7 +471,7 @@ impl Default for ToolOptions { cam_mode: "move".into(), cam_structure: 4.0, cam_color: 0.0, - cam_transform_on_drop: false, + cam_transform_on_drop: true, tone_range: "midtones".into(), exposure: 50.0, protect_tones: true, @@ -522,16 +534,19 @@ impl Default for ToolOptions { bg_limits: "contiguous".into(), bg_tolerance: 50.0, bg_protect_fg: false, + bg_tolerance_control: "penPressure".into(), cr_mode: "color".into(), cr_sampling: "continuous".into(), cr_limits: "contiguous".into(), cr_tolerance: 30.0, cr_anti_alias: true, zoom_scrubby: true, + hand_scroll_all: false, pencil_auto_erase: false, brush_clear: false, pencil_clear: false, eraser_mode: default_eraser_mode(), + mixer_combination: 0, magnetic_width: 10.0, magnetic_contrast: 10.0, magnetic_frequency: 57.0, @@ -547,3 +562,7 @@ impl Default for ToolOptions { } } } + +#[cfg(test)] +#[path = "../cam_transform_on_drop_default_tests.rs"] +mod cam_transform_on_drop_default_tests; diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index ed59943fae..b26d776a4d 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -366,7 +366,7 @@ fn a_committed_stroke_repaints_a_gradient_overlay_over_the_whole_layer() { let c = app.committed_stroke.as_ref().expect("the commit took the live stroke's pixels"); assert_eq!(c.revision, st.revision); // A cache that showed the live stroke's last step. - let missed = crate::canvas::damage_since(app, idx, (st.revision - 1, c.last_key()), (st.revision, 0), 0, st.last_damage).unwrap(); + let missed = crate::canvas::damage_since(app, idx, (st.revision - 1, c.last_key()), (st.revision, 0), 0, (st.damage_from(), st.last_damage)).unwrap(); assert!(missed.contains(25, 25), "the gradient around the first stroke is repainted: {missed:?}"); } @@ -390,7 +390,7 @@ fn the_stroke_trace_times_each_frame_of_a_stroke_and_ends_on_release() { app.perf.stage.start(t0, moves); app.perf.stage.ui_start(t0, Some(0.004)); egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); - app.finish_frame(crate::gpu_canvas::now_ms() - t0); + app.finish_frame(&ctx, crate::gpu_canvas::now_ms() - t0); }, app, ); diff --git a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs index 83c3ca33cc..e49077c4ff 100644 --- a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs +++ b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs @@ -160,5 +160,5 @@ fn a_plain_w_from_outside_the_group_keeps_selecting_what_it_selected_before() { ctx.begin_pass(raw); crate::shortcuts::handle(&mut app, &ctx); ctx.end_pass().textures_delta.clear(); - assert_eq!(app.ui.tool, Tool::MagicWand, "the first W tool in Tool::ALL, not the first in the flyout"); + assert_eq!(app.ui.tool, Tool::ObjectSelection, "fresh W selects the first tool in the flyout"); } diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 9878bf41a4..b921d98268 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -2,8 +2,10 @@ pub(super) mod align_bar; pub mod analysis_ui; pub mod anchor_tools; pub mod artboard_tool; +pub mod bg_eraser_popup; pub(crate) mod brush_cursor; pub mod brush_picker; +pub mod brush_refusal; pub mod brush_resize; pub(super) mod cam_transform; pub mod cas_transform; @@ -56,5 +58,7 @@ pub mod vector_ui; pub mod warp_preview; pub mod zoom_tool; +#[cfg(test)] +mod count_show_extras_tests; #[cfg(test)] mod crop_options_labels_tests; diff --git a/crates/ui-egui/src/tools/analysis_ruler_shift_tests.rs b/crates/ui-egui/src/tools/analysis_ruler_shift_tests.rs new file mode 100644 index 0000000000..301636845f --- /dev/null +++ b/crates/ui-egui/src/tools/analysis_ruler_shift_tests.rs @@ -0,0 +1,101 @@ +//! Shift constrains the Ruler to 45° steps without making it longer (#11985): on a diagonal step +//! both legs take min(|dx|, |dy|), on a 0° or 90° step the dominant component stays and the other +//! is 0; the same for an endpoint moved around the other one and for a protractor's second arm. + +use egui::Modifiers; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; +use photocraft_engine::doc::Ruler; + +fn ruler_app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.ui.tool = Tool::Ruler; + app +} + +/// A drag from `from` to `to` with `m` held during the move. +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], press: Modifiers, m: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, press); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); +} + +fn ruler(app: &PhotocraftApp) -> Ruler { + app.session.active().unwrap().doc.measurement.ruler.expect("a ruler") +} + +fn info(app: &PhotocraftApp) -> Value { + photocraft_engine::analysis_cmds::ruler_info(&ruler(app), &Default::default()) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 0.01 +} + +#[test] +fn drawing_with_shift_keeps_the_shorter_leg_on_diagonals_and_the_dominant_one_on_axes() { + // (pointer, constrained end, L1 when measured), all from 100,100. + for (to, end, l1) in [ + ([182.0, 200.0], [182.0, 182.0], Some(115.97)), + ([222.0, 220.0], [220.0, 220.0], None), + ([400.0, 130.0], [400.0, 100.0], None), + // Signs are kept: dx −82, dy −100. + ([18.0, 0.0], [18.0, 18.0], None), + ] { + let mut app = ruler_app(); + drag(&mut app, [100.0, 100.0], to, Modifiers::NONE, Modifiers::SHIFT); + let r = ruler(&app); + assert_eq!(r.start, [100.0, 100.0]); + assert!(near(r.end[0], end[0]) && near(r.end[1], end[1]), "to {to:?}: end {:?}, expected {end:?}", r.end); + if let Some(l1) = l1 { + let i = info(&app); + assert!(near(i["w"].as_f64().unwrap().abs(), 82.0) && near(i["h"].as_f64().unwrap().abs(), 82.0), "{i}"); + assert!(near(i["l1"].as_f64().unwrap(), l1), "{i}"); + } + assert_eq!(app.session.active().unwrap().history.past_len(), 0, "no history step"); + } +} + +#[test] +fn moving_an_endpoint_with_shift_snaps_around_the_other_one() { + // The end point, around the start. + let mut app = ruler_app(); + drag(&mut app, [100.0, 100.0], [300.0, 250.0], Modifiers::NONE, Modifiers::NONE); + drag(&mut app, [300.0, 250.0], [382.0, 160.0], Modifiers::NONE, Modifiers::SHIFT); + let r = ruler(&app); + assert_eq!((r.start, r.end), ([100.0, 100.0], [382.0, 100.0]), "W 282, H 0"); + // The start point, around the end. + let mut app = ruler_app(); + drag(&mut app, [100.0, 100.0], [400.0, 300.0], Modifiers::NONE, Modifiers::NONE); + drag(&mut app, [100.0, 100.0], [118.0, 240.0], Modifiers::NONE, Modifiers::SHIFT); + let r = ruler(&app); + assert_eq!((r.start, r.end), ([118.0, 300.0], [400.0, 300.0]), "W 282, H 0"); +} + +#[test] +fn a_protractor_arm_with_shift_keeps_the_shorter_leg() { + let mut app = ruler_app(); + drag(&mut app, [400.0, 300.0], [600.0, 300.0], Modifiers::NONE, Modifiers::NONE); + // Shift+Alt-drag from the vertex: pointer at +62, −80. + drag(&mut app, [400.0, 300.0], [462.0, 220.0], Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT); + let arm = ruler(&app).protractor.expect("a protractor"); + assert!(near(arm[0], 462.0) && near(arm[1], 238.0), "{arm:?}"); + let i = info(&app); + assert!(near(i["l2"].as_f64().unwrap(), 87.68), "{i}"); + // Shift-drag that arm end to dx 122, dy −170 from the vertex. + drag(&mut app, [462.0, 238.0], [522.0, 130.0], Modifiers::NONE, Modifiers::SHIFT); + let arm = ruler(&app).protractor.unwrap(); + assert!(near(arm[0], 522.0) && near(arm[1], 178.0), "{arm:?}"); + assert!(near(info(&app)["l2"].as_f64().unwrap(), 172.53)); +} + +#[test] +fn without_shift_the_endpoint_follows_the_pointer() { + let mut app = ruler_app(); + drag(&mut app, [100.0, 100.0], [182.0, 200.0], Modifiers::NONE, Modifiers::NONE); + assert_eq!(ruler(&app).end, [182.0, 200.0]); +} diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index a3b9826acb..a60b60e832 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -7,6 +7,10 @@ //! part of the serialisable UI state so the control channel can read and drive it). The Color //! Sampler points themselves live in the engine (`DocState.color_samplers`) so every front end //! shares them; this module only maps pointer input and draws the numbered markers. +//! +//! The Ruler options bar's Straighten Layer button is on when the engine's check says so, and a +//! hidden target layer answers its click with the reference's alert rather than the status line +//! (#12033). use egui::{Align2, Color32, CornerRadius, FontId, Pos2, RichText, Stroke, pos2, vec2}; use photocraft_doc::{Document, Ruler}; @@ -15,7 +19,7 @@ use serde_json::{Map, Value, json}; use crate::PhotocraftApp; use crate::canvas::{ToolEvent, ViewXform}; -use crate::state::Tool; +use crate::state::{DialogKind, Tool}; use crate::theme::Tokens; /// What a pointer drag is doing (not serialised). @@ -68,7 +72,7 @@ impl Default for AnalysisUi { log_selected: Vec::new(), note_selected: None, note_author: String::new(), - note_color: [1.0, 1.0, 0.51], + note_color: photocraft_engine::notes_cmds::DEFAULT_NOTE_COLOR, use_measurement_scale: false, dialog: None, drag: None, @@ -219,15 +223,24 @@ fn dist(a: [f64; 2], b: [f64; 2]) -> f64 { (a[0] - b[0]).hypot(a[1] - b[1]) } -/// Shift constrains to 45° steps around `from`. +/// Shift constrains to 45° steps around `from`, as the reference does (#11985): on a diagonal step +/// both legs take the smaller of |dx| and |dy| (signs kept), on a 0° or 90° step the dominant +/// component stays and the other becomes 0, so the ruler never gets longer than the pointer's legs. fn constrain(from: [f64; 2], to: [f64; 2], shift: bool) -> [f64; 2] { if !shift { return to; } let (dx, dy) = (to[0] - from[0], to[1] - from[1]); - let a = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; - let l = dx.hypot(dy); - [from[0] + l * a.cos(), from[1] + l * a.sin()] + let step = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() as i64; + let (cx, cy) = match step.rem_euclid(4) { + 0 => (dx, 0.0), + 2 => (0.0, dy), + _ => { + let leg = dx.abs().min(dy.abs()); + (leg.copysign(dx), leg.copysign(dy)) + } + }; + [from[0] + cx, from[1] + cy] } fn set_ruler(app: &mut PhotocraftApp, r: Ruler) { @@ -315,7 +328,10 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> } Some((g, i)) => app.ui.analysis.drag = Some(Drag::Count(g, i, [x, y])), None if !mods.alt => { - let _ = app.run("count.add", json!({"x": x, "y": y})); + // A marker that stays invisible looks like the click did nothing, so adding one + // brings View > Show > Count back. It is view state, not a history step. + let added = app.run("count.add", json!({"x": x, "y": y})).is_ok(); + app.ui.view.show.count |= added; } None => {} } @@ -547,8 +563,26 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::vline(ui, 22.0); crate::widgets::checkbox(ui, &mut app.ui.analysis.use_measurement_scale, tl!("Use Measurement Scale")); let has = doc.measurement.ruler.is_some(); - if ui.add_enabled_ui(has, |ui| crate::widgets::secondary_button(ui, tl!("Straighten Layer"), 0.0)).inner.clicked() { - let _ = app.run("image.analysis.straightenLayer", json!({})); + // The engine decides this button's state, so it goes grey for exactly the targets + // Straighten Layer is off for: the Background, several selected layers, a group and a + // layer locked in place (#12033). + let straighten = app.session.is_enabled("image.analysis.straightenLayer"); + if ui.add_enabled_ui(straighten, |ui| crate::widgets::secondary_button(ui, tl!("Straighten Layer"), 0.0)).inner.clicked() { + let hidden = photocraft_engine::analysis_cmds::STRAIGHTEN_HIDDEN_ERROR; + if let Err(why) = app.run("image.analysis.straightenLayer", json!({})) { + // A hidden target layer keeps the button on and answers the click with the + // reference's alert (its message and an OK button), changing nothing (#12033). + if why == hidden { + app.ui.open_dialog(DialogKind::Error, json!({"message": tl!(hidden)}).as_object().cloned().unwrap_or_default()); + } + // Every other refusal goes to the status line, as the eraser tools do. What the + // command itself answered is reported there by `PhotocraftApp::run`, but a + // refusal raised before it runs - the automation gate a control or MCP-driven + // click passes - returns early, and a click that says nothing reads as a dead + // button (#12148). + app.ui.status = why; + app.ui.status_error = true; + } } if ui.add_enabled_ui(has, |ui| crate::widgets::secondary_button(ui, tl!("Clear"), 0.0)).inner.clicked() { let _ = app.run("image.analysis.rulerTool", json!({"clear": true})); @@ -614,9 +648,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo if crate::widgets::color_swatch_button(ui, color32(rgb), tl!("Color")).clicked() { crate::color_picker_ui::open_for_target(app, "noteColor", &crate::color_picker_ui::title_for(tl!("Color")), rgb); } + // Clear All asks first (#11791); `notes.delete {"all": true}` itself never does. if ui.add_enabled_ui(!doc.notes.is_empty(), |ui| crate::widgets::secondary_button(ui, tl!("Clear All"), 0.0)).inner.clicked() { - let _ = app.run("notes.delete", json!({"all": true})); - app.ui.analysis.note_selected = None; + ask_clear_notes(app); } if crate::icons::button(ui, "message-square", 22.0, app.ui.analysis.notes, tl!("Show or hide the Notes panel")).clicked() { app.ui.analysis.notes = !app.ui.analysis.notes; @@ -1024,6 +1058,45 @@ mod sampler_drag_tests; /// Marks the "Delete this note?" alert (#11788). const DELETE_NOTE_MARK: &str = "__deleteNote"; + +/// Marks the "Are you sure you want to delete all notes?" alert (#11791). +const CLEAR_NOTES_MARK: &str = "__clearAllNotes"; + +/// The Note tool's Clear All: Photoshop's alert, OK / Cancel (#11791). OK deletes every note in one +/// "Delete all Notes" step; Cancel (or Escape) changes nothing. +pub fn ask_clear_notes(app: &mut PhotocraftApp) { + let Some(doc) = app.session.active().filter(|s| !s.doc.notes.is_empty()).map(|s| s.doc.id.0) else { return }; + if app.ui.dialogs.iter().any(|d| owns_clear_notes(&d.fields)) { + return; + } + let mut f = Map::new(); + f.insert(CLEAR_NOTES_MARK.into(), json!(true)); + f.insert("__command".into(), json!("notes.delete")); + f.insert("__label".into(), json!(tl!("Clear All"))); + f.insert("document".into(), json!(doc)); + app.ui.open_dialog(crate::state::DialogKind::Command, f); +} + +pub fn owns_clear_notes(fields: &Map) -> bool { + fields.contains_key(CLEAR_NOTES_MARK) +} + +pub fn clear_notes_body(ui: &mut egui::Ui) { + ui.label(tl!("Are you sure you want to delete all notes?")); +} + +/// OK: every note goes in one step, nothing stays selected, and the options bar shows the tool +/// defaults again (a selected note had put its author and colour there). +pub fn confirm_clear_notes(app: &mut PhotocraftApp, fields: &Map) -> Result { + if app.session.active().map(|s| s.doc.id.0) != fields.get("document").and_then(Value::as_u64) { + return Err(tl!("The document changed. Please choose Clear All again.").into()); + } + let result = app.run("notes.delete", json!({"all": true}))?; + let defaults = AnalysisUi::default(); + let a = &mut app.ui.analysis; + (a.note_selected, a.note_author, a.note_color) = (None, defaults.note_author, defaults.note_color); + Ok(result) +} /// Its "Don't show again", kept with the other dialog preferences. const DELETE_NOTE_PREF: &str = "notes.delete.confirmation"; @@ -1125,3 +1198,11 @@ pub fn note_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { #[cfg(test)] #[path = "note_delete_key_tests.rs"] mod note_delete_key_tests; + +#[cfg(test)] +#[path = "analysis_ruler_shift_tests.rs"] +mod analysis_ruler_shift_tests; + +#[cfg(test)] +#[path = "note_clear_all_tests.rs"] +mod note_clear_all_tests; diff --git a/crates/ui-egui/src/tools/analysis_ui/tests.rs b/crates/ui-egui/src/tools/analysis_ui/tests.rs index 3ed65a3ffd..517e7df649 100644 --- a/crates/ui-egui/src/tools/analysis_ui/tests.rs +++ b/crates/ui-egui/src/tools/analysis_ui/tests.rs @@ -296,3 +296,147 @@ fn count_size_fields_send_whole_numbers_the_engine_applies() { let g = &app.session.active().unwrap().doc.measurement.count_groups[0]; assert_eq!((g.marker_size, g.label_size), (8, 20)); } + +// ---------------------------------------------------------------- Straighten Layer button (#12033) + +/// The Ruler options bar, drawn wide enough for its buttons to show. +fn ruler_bar(mut app: PhotocraftApp) -> egui_kittest::Harness<'static, PhotocraftApp> { + use egui::vec2; + app.ui.tool = Tool::Ruler; + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 60.0)).build_ui_state( + |ui: &mut egui::Ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Pro); + h.run_steps(4); + h +} + +/// A ruler line to straighten by, without one the button is off for every target. +fn rule(app: &mut PhotocraftApp) { + app.run("image.analysis.rulerTool", json!({"start": [10, 30], "end": [150, 25]})).unwrap(); +} + +/// The message of every open error dialog, in the order they were opened. +fn alerts(app: &PhotocraftApp) -> Vec<&str> { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(|m| m.as_str())).collect() +} + +/// Each case opens one of the targets #12033 measured, on top of the plain document `app()` makes. +fn add_layer(app: &mut PhotocraftApp, name: &str) -> u64 { + app.run("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap() +} + +fn on_a_layer(app: &mut PhotocraftApp) { + add_layer(app, "Paint"); +} + +fn on_the_background(_: &mut PhotocraftApp) {} + +fn on_two_layers(app: &mut PhotocraftApp) { + let a = add_layer(app, "One"); + let b = add_layer(app, "Two"); + app.run("layer.select", json!({"layer": a})).unwrap(); + app.run("layer.select", json!({"layer": b, "mode": "add"})).unwrap(); +} + +fn on_a_group(app: &mut PhotocraftApp) { + add_layer(app, "Inner"); + app.run("layer.groupLayers", json!({})).unwrap(); +} + +fn locked(app: &mut PhotocraftApp, key: &str) { + let l = add_layer(app, "Colors"); + app.run("layer.setProps", json!({"layer": l, "locks": {key: true}})).unwrap(); +} + +fn on_lock_all(app: &mut PhotocraftApp) { + locked(app, "all"); +} + +fn on_lock_position(app: &mut PhotocraftApp) { + locked(app, "position"); +} + +/// #12033: the options bar asks the engine, so the button is greyed out for exactly the targets +/// `image.analysis.straightenLayer` is off for - the Background, two or more selected layers, a +/// group, Lock All and Lock Position - and live for a layer. +#[test] +fn the_straighten_layer_button_greys_out_where_the_command_is_off() { + use egui_kittest::kittest::{NodeT, Queryable}; + type Case = (&'static str, fn(&mut PhotocraftApp), bool); + let cases: [Case; 6] = [ + ("a pixel layer", on_a_layer, true), + ("the Background", on_the_background, false), + ("two selected layers", on_two_layers, false), + ("a group", on_a_group, false), + ("Lock All", on_lock_all, false), + ("Lock Position", on_lock_position, false), + ]; + for (what, prepare, live) in cases { + let (mut app, _) = app(); + prepare(&mut app); + rule(&mut app); + let h = ruler_bar(app); + assert_eq!(h.state().session.is_enabled("image.analysis.straightenLayer"), live, "{what}: the command's own check"); + let button = h.get_by_label("Straighten Layer").accesskit_node(); + assert_eq!(!button.is_disabled(), live, "{what}: the options-bar button follows the command"); + // The other Ruler button is unaffected: a ruler line is there to clear in every state. + assert!(!h.get_by_label("Clear").accesskit_node().is_disabled(), "{what}: Clear stays on"); + } +} + +/// A refused click says so. `PhotocraftApp::run` reports what the *command* answered in the status +/// line, but a refusal raised before it runs - the automation gate a control/MCP-driven click goes +/// through - returns early, so the button has to report it itself. As the toolbar flyout does +/// (`a_failed_edit_toolbar_from_the_flyout_reports_its_error_in_the_status_bar`). +#[test] +fn a_denied_synthetic_click_reports_the_refusal_instead_of_saying_nothing() { + use egui_kittest::kittest::{NodeT, Queryable}; + let (mut app, _) = app(); + on_a_layer(&mut app); + rule(&mut app); + app.automation_input = true; + app.services.automation_command = + Some(Box::new(|id, _| if id == "image.analysis.straightenLayer" { Err("straightening is denied".into()) } else { Ok(()) })); + let mut h = ruler_bar(app); + assert!(!h.get_by_label("Straighten Layer").accesskit_node().is_disabled(), "the layer is a valid target"); + let steps = h.state().session.active().unwrap().history.past_len(); + h.get_by_label("Straighten Layer").click(); + h.run_steps(2); + let st = h.state(); + assert_eq!(st.ui.status, "straightening is denied", "the refusal reaches the status line"); + assert!(st.ui.status_error, "as an error"); + assert!(alerts(st).is_empty(), "the alert stays the hidden layer's own"); + let now = st.session.active().unwrap(); + assert!(now.doc.measurement.ruler.is_some(), "nothing ran: the ruler line is still up"); + assert_eq!(now.history.past_len(), steps, "and nothing was recorded"); +} + +/// #12033: a hidden target layer is the one state that keeps its button. The click answers with the +/// reference's alert - its measured message and an OK button - instead of the status line, and the +/// document, its History and the ruler line stay as they were. +#[test] +fn a_hidden_layer_keeps_the_button_and_the_click_shows_the_alert() { + use egui_kittest::kittest::{NodeT, Queryable}; + let (mut app, _) = app(); + let l = app.run("layer.new.layer", json!({"name": "Gone"})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.setProps", json!({"layer": l, "visible": false})).unwrap(); + rule(&mut app); + let mut h = ruler_bar(app); + assert!(!h.get_by_label("Straighten Layer").accesskit_node().is_disabled(), "a hidden layer keeps the button on"); + let (before, steps) = (h.state().session.active().unwrap().doc.clone(), h.state().session.active().unwrap().history.past_len()); + h.get_by_label("Straighten Layer").click(); + h.run_steps(2); + let st = h.state(); + assert_eq!(alerts(st), [photocraft_engine::analysis_cmds::STRAIGHTEN_HIDDEN_ERROR], "one alert with the reference's text"); + let now = st.session.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &now.doc), "the document was not touched"); + assert_eq!(now.history.past_len(), steps, "no History step"); + assert!(now.doc.measurement.ruler.is_some(), "the ruler line is still there"); +} diff --git a/crates/ui-egui/src/tools/bg_eraser_popup.rs b/crates/ui-egui/src/tools/bg_eraser_popup.rs new file mode 100644 index 0000000000..d59c55197e --- /dev/null +++ b/crates/ui-egui/src/tools/bg_eraser_popup.rs @@ -0,0 +1,122 @@ +//! The Background Eraser's compact brush popup (#11910): what its options-bar brush picker and a +//! canvas right-click open instead of the Brush Preset picker, as in Photoshop. No preset list and +//! no search field; top to bottom Size, Hardness and Spacing (fields with sliders), the +//! angle/roundness widget, Angle and Roundness fields, then the "Size:" and "Tolerance:" pen +//! dropdowns (Off · Pen Pressure · Stylus Wheel), the latter with the reference's tablet warning. +//! +//! It edits the caller's copy of the brush like the picker does (`paint_mouse` commits it through +//! `tools.setBrush`); the Tolerance control is a tool option (`ToolOptions::bg_tolerance_control`). + +use egui::{RichText, vec2}; +use photocraft_engine::BrushSettings; +use photocraft_engine::paint::{Control, MAX_BRUSH_SIZE, TipShape}; + +use crate::theme::Tokens; +use crate::widgets; + +/// The pen dropdowns' entries, as stored. +pub const OFF: &str = "off"; +pub const PEN_PRESSURE: &str = "penPressure"; +pub const STYLUS_WHEEL: &str = "stylusWheel"; +/// The tooltip of the warning triangle next to "Tolerance:". +pub const PRESSURE_WARNING: &str = "Control by pen pressure requires the use of a pressure sensitive tablet"; + +/// The popup's width. +pub const WIDTH: f32 = 240.0; + +fn pen_options() -> [(String, &'static str); 3] { + [(OFF.into(), tl!("Off")), (PEN_PRESSURE.into(), tl!("Pen Pressure")), (STYLUS_WHEEL.into(), tl!("Stylus Wheel"))] +} + +/// What the brush's "Size:" control is: Pen Pressure is the brush's pressure-for-size switch, +/// Stylus Wheel its Shape Dynamics size control. +pub fn size_control(b: &BrushSettings) -> &'static str { + if b.pressure_size { + PEN_PRESSURE + } else if b.shape_dynamics.enabled && b.shape_dynamics.size.control == Control::StylusWheel { + STYLUS_WHEEL + } else { + OFF + } +} + +/// Set the brush's "Size:" control. +pub fn set_size_control(b: &mut BrushSettings, control: &str) { + b.pressure_size = control == PEN_PRESSURE; + if control == STYLUS_WHEEL { + b.shape_dynamics.enabled = true; + b.shape_dynamics.size.control = Control::StylusWheel; + } else if b.shape_dynamics.size.control == Control::StylusWheel { + b.shape_dynamics.size.control = Control::Off; + } +} + +/// The popup's controls, editing `b` and the tool's Tolerance control. +pub fn body(ui: &mut egui::Ui, b: &mut BrushSettings, tolerance_control: &mut String) { + let t = Tokens::get(ui.ctx()); + ui.set_width(WIDTH); + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Size")).color(t.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut size = b.size; + if widgets::value_field(ui, &mut size, 1.0..=MAX_BRUSH_SIZE, "px", 72.0).accessible_name(tl!("Size")).changed() { + b.size = size.round().clamp(1.0, MAX_BRUSH_SIZE); + } + }); + }); + // Logarithmic, as the Brush Preset picker's: small sizes get most of the travel. + let mut lv = b.size.max(1.0).ln(); + if widgets::slider(ui, &mut lv, 0.0..=MAX_BRUSH_SIZE.ln(), None).changed() { + b.size = lv.exp().round().clamp(1.0, MAX_BRUSH_SIZE); + } + if b.tip == TipShape::Round { + let mut hard = b.hardness * 100.0; + if widgets::slider_row(ui, "Hardness", &mut hard, 0.0..=100.0, "%", None).changed() { + b.hardness = (hard / 100.0).clamp(0.0, 1.0); + } + } + let mut spacing = b.spacing * 100.0; + if widgets::slider_row(ui, "Spacing", &mut spacing, 1.0..=1000.0, "%", None).changed() { + b.spacing = (spacing / 100.0).clamp(0.01, 10.0); + } + ui.add_space(4.0); + ui.horizontal(|ui| { + crate::brush_sections::ellipse_widget(ui, &mut b.angle, &mut b.roundness); + ui.vertical(|ui| { + let mut angle = b.angle; + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Angle:")).color(t.text_dim)); + if widgets::value_field(ui, &mut angle, -180.0..=180.0, "°", 64.0).accessible_name(tl!("Angle")).changed() && angle.is_finite() { + b.angle = angle.round().clamp(-180.0, 180.0); + } + }); + let mut round = b.roundness * 100.0; + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Roundness:")).color(t.text_dim)); + if widgets::value_field(ui, &mut round, 0.0..=100.0, "%", 64.0).accessible_name(tl!("Roundness")).changed() && round.is_finite() { + b.roundness = (round / 100.0).clamp(0.0, 1.0); + } + }); + }); + }); + ui.add_space(4.0); + let options = pen_options(); + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Size:")).color(t.text_dim)); + let mut size = size_control(b).to_string(); + if widgets::dropdown(ui, "bg-eraser-size-control", tl!("Size:"), &mut size, &options, 120.0) { + set_size_control(b, &size); + } + }); + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Tolerance:")).color(t.text_dim)); + widgets::dropdown(ui, "bg-eraser-tolerance-control", tl!("Tolerance:"), tolerance_control, &options, 120.0); + let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), egui::Sense::hover()); + crate::icons::paint(ui, r, "triangle-alert", 14.0, t.warning); + resp.on_hover_text(tl!(PRESSURE_WARNING)).widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, tl!(PRESSURE_WARNING))); + }); +} + +#[cfg(test)] +#[path = "../background_eraser_brush_popup_tests.rs"] +mod background_eraser_brush_popup_tests; diff --git a/crates/ui-egui/src/tools/brush_picker.rs b/crates/ui-egui/src/tools/brush_picker.rs index 3e59a90444..298a300a83 100644 --- a/crates/ui-egui/src/tools/brush_picker.rs +++ b/crates/ui-egui/src/tools/brush_picker.rs @@ -7,13 +7,13 @@ //! click picks a preset and keeps the picker open, a double-click picks it and closes the picker //! (#1031); drag to reorder, right-click to rename or delete. Each card is a 2 × 2 grid — tip at //! the top left, stroke preview at the top right and the name in the merged bottom row (or in the -//! stroke's cell when only the tip and the name show) — and the gear's three boxes ([`body`]'s -//! Brush Name/Brush Stroke/Brush Tip) hide its parts, at least one always on; the footer slider -//! scales the cards. Its view state (search, collapsed groups, the card's parts, the footer -//! scale, a rename in progress) is `UiState::brush_picker_list`, so the control channel can read -//! and set it. The gear's parts and the footer scale are remembered across restarts -//! ([`persist`]/[`restore`], `Preferences::brush_picker`); the search, collapsed groups and a -//! rename in progress are not. +//! stroke's cell when only the tip and the name show) — and the gear's three boxes ([`GEAR_MENU`]'s +//! Brush Name/Brush Stroke/Brush Tip; the tip off at first, as in Photoshop) hide its parts, at +//! least one always on; the footer slider scales the cards. Its view state (search, collapsed +//! groups, the card's parts, the search bar, the footer scale, a rename in progress) is +//! `UiState::brush_picker_list`, so the control channel can read and set it. The gear's parts, +//! Show Search Bar and the footer scale are remembered across restarts ([`persist`]/[`restore`], +//! `Preferences::brush_picker`); the search, collapsed groups and a rename in progress are not. //! //! The picker edits a copy of the brush; the caller sends the size and hardness edits through //! `tools.setBrush` ([`crate::brush_panel::commit_gesture`]) and applies the returned [`Pick`]s @@ -91,31 +91,44 @@ pub(crate) fn opened_id() -> egui::Id { picker_id().with("opened-with") } -/// What Escape in the picker goes back to (#11816): the Size and Hardness it opened with (or a -/// picked preset brought), and the values its own fields last typed. Escape reverts a value only -/// while it is still the typed one, so a change from elsewhere (`]`, the options bar) stays. +/// What Escape in the picker goes back to (#11816): the Size, Hardness, Angle and Roundness it +/// opened with (or a picked preset brought), and the values its own controls last set. Escape +/// reverts a value only while it is still the picker's, so a change from elsewhere (`]`, the +/// options bar) stays. Angle and Roundness come from the tip widget (#11821). #[derive(Clone, Debug, Default, PartialEq)] pub(crate) struct Opened { - opened: [f32; 2], - typed: [f32; 2], + opened: [f32; 4], + typed: [f32; 4], +} + +fn picker_values(b: &photocraft_engine::BrushSettings) -> [f32; 4] { + [b.size, b.hardness, b.angle, b.roundness] } impl Opened { pub(crate) fn new(b: &photocraft_engine::BrushSettings) -> Self { - Self { opened: [b.size, b.hardness], typed: [b.size, b.hardness] } + Self { opened: picker_values(b), typed: picker_values(b) } } pub(crate) fn typed(&mut self, b: &photocraft_engine::BrushSettings) { - self.typed = [b.size, b.hardness]; + self.typed = picker_values(b); } pub(crate) fn revert(&self, now: &photocraft_engine::BrushSettings) -> photocraft_engine::BrushSettings { let mut b = now.clone(); - if b.size == self.typed[0] { - b.size = self.opened[0]; + let [size, hardness, angle, roundness] = self.opened; + let [typed_size, typed_hardness, typed_angle, typed_roundness] = self.typed; + if b.size == typed_size { + b.size = size; } - if b.hardness == self.typed[1] { - b.hardness = self.opened[1]; + if b.hardness == typed_hardness { + b.hardness = hardness; + } + if b.angle == typed_angle { + b.angle = angle; + } + if b.roundness == typed_roundness { + b.roundness = roundness; } b } @@ -138,16 +151,18 @@ pub fn close(ui: &mut crate::state::UiState) { ui.brush_picker_list.renaming = None; } -/// The state the picker's preset list starts from: every card part on (tip, stroke and name). +/// The state the picker's preset list starts from: the cards show the name and the stroke, not the +/// tip, and the search bar shows (Photoshop's defaults). The Brushes panel keeps +/// [`BrushesPanelState::default`]. pub fn list_state() -> BrushesPanelState { - BrushesPanelState::default() + BrushesPanelState { show_tip: false, ..BrushesPanelState::default() } } -/// The picker's view remembered across restarts: the gear's three card parts and the footer -/// scale (`Preferences::brush_picker`). +/// The picker's view remembered across restarts: the gear's three card parts, Show Search Bar and +/// the footer scale (`Preferences::brush_picker`). fn view(app: &PhotocraftApp) -> Value { let st = &app.ui.brush_picker_list; - json!({"showName": st.show_name, "showStroke": st.show_stroke, "showTip": st.show_tip, "scale": st.scale}) + json!({"showName": st.show_name, "showStroke": st.show_stroke, "showTip": st.show_tip, "showSearch": st.show_search, "scale": st.scale}) } /// Remember the picker's view in the preferences once the user lets go of the pointer: the @@ -166,7 +181,7 @@ pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { /// Restore the picker's remembered view at launch. A missing or malformed part keeps its /// default, the scale is clamped to the slider's range, and the three parts can't all come -/// back off (an empty card would show no brush at all). +/// back off (an empty card would show no brush at all): then they get [`list_state`]'s. pub fn restore(app: &mut PhotocraftApp) { let saved = app.session.prefs().brush_picker.clone(); let st = &mut app.ui.brush_picker_list; @@ -179,13 +194,17 @@ pub fn restore(app: &mut PhotocraftApp) { if let Some(v) = saved.get("showTip").and_then(Value::as_bool) { st.show_tip = v; } + if let Some(v) = saved.get("showSearch").and_then(Value::as_bool) { + st.show_search = v; + } if let Some(v) = saved.get("scale").and_then(Value::as_f64) && v.is_finite() { st.scale = (v as f32).clamp(*SCALE_RANGE.start(), *SCALE_RANGE.end()); } if ![st.show_name, st.show_stroke, st.show_tip].into_iter().any(|b| b) { - (st.show_name, st.show_stroke, st.show_tip) = (true, true, true); + let d = list_state(); + (st.show_name, st.show_stroke, st.show_tip) = (d.show_name, d.show_stroke, d.show_tip); } } @@ -238,7 +257,8 @@ pub(crate) fn named(resp: egui::Response, label: &str) -> egui::Response { } /// The picker's contents: Size, Hardness (round tips only: a sampled tip has none), a search -/// field with the Brush Settings, New Preset and gear buttons, the preset list, and the footer +/// field (unless the gear's Show Search Bar is off) with the Brush Settings, New Preset and gear +/// buttons, the preset list, and the footer /// slider that scales the cards ([`scale_slider`]). Size and Hardness sit in a block flush with /// the left edge, at most [`HEAD_MAX_W`] wide, so a picker dragged wider doesn't stretch them. /// `current` is the selected preset's name (by identity, so edits don't deselect). `size` is the @@ -260,43 +280,64 @@ pub fn body( ui.set_width(size.x); ui.set_min_height(size.y); let top = ui.cursor().min.y; - // The Size and Hardness controls live in one block flush with the left edge, at most - // [`HEAD_MAX_W`] wide: a picker dragged wider leaves the space past the block empty instead of - // stretching the rows across it. - ui.scope(|ui| { - ui.set_max_width(ui.available_width().min(HEAD_MAX_W)); - // Size: value field plus a logarithmic slider (small sizes get most of the travel). - ui.horizontal(|ui| { - ui.label(RichText::new(tl!("Size")).color(t.text_dim)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut size = b.size; - if widgets::value_field(ui, &mut size, 1.0..=MAX_BRUSH_SIZE, "px", 72.0).accessible_name(tl!("Size")).changed() { - b.size = size.round().clamp(1.0, MAX_BRUSH_SIZE); - } + // The tip's angle/roundness widget at the top left (#11821), then the Size and Hardness + // controls in one block, at most [`HEAD_MAX_W`] wide: a picker dragged wider leaves the space + // past the block empty instead of stretching the rows across it. + ui.horizontal_top(|ui| { + let (angle, roundness) = (b.angle, b.roundness); + crate::brush_sections::ellipse_widget(ui, &mut b.angle, &mut b.roundness); + // A pointer position that isn't finite leaves the tip as it was. + let finite = |p: egui::Pos2| p.x.is_finite() && p.y.is_finite(); + let pointer_ok = ui.input(|i| i.pointer.interact_pos().is_none_or(finite) && i.pointer.latest_pos().is_none_or(finite)); + if !(pointer_ok && b.angle.is_finite() && b.roundness.is_finite()) { + (b.angle, b.roundness) = (angle, roundness); + } + ui.vertical(|ui| { + ui.set_max_width(ui.available_width().min(HEAD_MAX_W)); + // Size: value field plus a logarithmic slider (small sizes get most of the travel). + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Size")).color(t.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut size = b.size; + if widgets::value_field(ui, &mut size, 1.0..=MAX_BRUSH_SIZE, "px", 72.0).accessible_name(tl!("Size")).changed() { + b.size = size.round().clamp(1.0, MAX_BRUSH_SIZE); + } + }); }); - }); - let mut lv = b.size.max(1.0).ln(); - let size_slider = widgets::slider(ui, &mut lv, 0.0..=MAX_BRUSH_SIZE.ln(), None); - if size_slider.changed() { - b.size = lv.exp().round().clamp(1.0, MAX_BRUSH_SIZE); - } - dismiss_popup(&size_slider); - if b.tip == TipShape::Round { - let mut hard = b.hardness * 100.0; - let hardness = widgets::slider_row(ui, "Hardness", &mut hard, 0.0..=100.0, "%", None); - if hardness.changed() { - b.hardness = (hard / 100.0).clamp(0.0, 1.0); + let mut lv = b.size.max(1.0).ln(); + let size_slider = widgets::slider(ui, &mut lv, 0.0..=MAX_BRUSH_SIZE.ln(), None); + if size_slider.changed() { + b.size = lv.exp().round().clamp(1.0, MAX_BRUSH_SIZE); } - dismiss_popup(&hardness); - } + dismiss_popup(&size_slider); + if b.tip == TipShape::Round { + let mut hard = b.hardness * 100.0; + let hardness = widgets::slider_row(ui, "Hardness", &mut hard, 0.0..=100.0, "%", None); + if hardness.changed() { + b.hardness = (hard / 100.0).clamp(0.0, 1.0); + } + dismiss_popup(&hardness); + } + }); }); ui.add_space(6.0); widgets::hairline(ui); ui.add_space(6.0); + // A hidden search bar filters nothing: a search typed before hiding it would otherwise keep + // presets out of the list with no field to show why. + if !st.show_search { + st.filter.clear(); + } ui.horizontal(|ui| { - icons::paint(ui, egui::Rect::from_min_size(ui.cursor().min + vec2(0.0, 3.0), vec2(16.0, 16.0)), "search", 14.0, t.text_faint); - ui.add_space(20.0); - widgets::text_field(ui, ui.scope_id().with("brush-picker-search"), &mut st.filter, tl!("Search Brushes"), (size.x - 118.0).max(60.0), false); + // In a scope of its own whether shown or not, so the buttons after it keep their ids and + // the gear's menu stays open when Show Search Bar takes the field away. + ui.scope(|ui| { + if st.show_search { + icons::paint(ui, egui::Rect::from_min_size(ui.cursor().min + vec2(0.0, 3.0), vec2(16.0, 16.0)), "search", 14.0, t.text_faint); + ui.add_space(20.0); + widgets::text_field(ui, ui.scope_id().with("brush-picker-search"), &mut st.filter, tl!("Search Brushes"), (size.x - 118.0).max(60.0), false); + } + }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { gear_menu(ui, current, presets, st, &mut picks); let new_tip = "Create new brush preset from the current settings"; @@ -389,8 +430,103 @@ pub fn resize_grip(ui: &mut egui::Ui, frame: egui::Rect, content: egui::Vec2) -> }) } -/// The gear: Photoshop's picker menu. A new preset, rename or delete the current one, the list's -/// view, and Import Brushes. +/// An entry of the gear menu ([`GEAR_MENU`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Gear { + NewPreset, + NewGroup, + Rename, + Delete, + Name, + Stroke, + Tip, + AdditionalInfo, + SearchBar, + RecentBrushes, + AppendDefaults, + Import, + ExportSelected, + GetMore, + LegacyToolPresets, + LegacyBrushes, +} + +impl Gear { + pub(crate) fn label(self) -> &'static str { + match self { + Gear::NewPreset => "New Brush Preset…", + Gear::NewGroup => "New Brush Group…", + Gear::Rename => "Rename Brush…", + Gear::Delete => "Delete Brush…", + Gear::Name => "Brush Name", + Gear::Stroke => "Brush Stroke", + Gear::Tip => "Brush Tip", + Gear::AdditionalInfo => "Show Additional Preset Info", + Gear::SearchBar => "Show Search Bar", + Gear::RecentBrushes => "Show Recent Brushes", + Gear::AppendDefaults => "Append Default Brushes…", + Gear::Import => "Import Brushes…", + Gear::ExportSelected => "Export Selected Brushes…", + Gear::GetMore => "Get More Brushes…", + Gear::LegacyToolPresets => "Converted Legacy Tool Presets", + Gear::LegacyBrushes => "Legacy Brushes", + } + } + + /// Does this entry act on the selected preset (greyed with none selected)? + pub(crate) fn needs_preset(self) -> bool { + matches!(self, Gear::Rename | Gear::Delete | Gear::ExportSelected) + } + + /// Is this entry only listed, its function still to come? It is greyed and does nothing. + /// New Brush Group…, Append Default Brushes…, Export Selected Brushes… and Legacy Brushes come + /// with the Brushes panel's library actions (#7450), Show Recent Brushes with the picker's + /// recent-brush bar (#7452). What Show Additional Preset Info, Get More Brushes… and Converted + /// Legacy Tool Presets do is not measured yet (#11819). + pub(crate) fn placeholder(self) -> bool { + matches!( + self, + Gear::NewGroup + | Gear::AdditionalInfo + | Gear::RecentBrushes + | Gear::AppendDefaults + | Gear::ExportSelected + | Gear::GetMore + | Gear::LegacyToolPresets + | Gear::LegacyBrushes + ) + } +} + +/// Photoshop's picker gear menu, top to bottom; `None` is a separator. +pub(crate) const GEAR_MENU: &[Option] = &[ + Some(Gear::NewPreset), + Some(Gear::NewGroup), + None, + Some(Gear::Rename), + Some(Gear::Delete), + None, + Some(Gear::Name), + Some(Gear::Stroke), + Some(Gear::Tip), + None, + Some(Gear::AdditionalInfo), + None, + Some(Gear::SearchBar), + Some(Gear::RecentBrushes), + None, + Some(Gear::AppendDefaults), + Some(Gear::Import), + Some(Gear::ExportSelected), + None, + Some(Gear::GetMore), + None, + Some(Gear::LegacyToolPresets), + Some(Gear::LegacyBrushes), +]; + +/// The gear: Photoshop's picker menu ([`GEAR_MENU`]). A new preset, rename or delete the current +/// one, the cards' parts, the search bar and Import Brushes; the entries still to come are greyed. fn gear_menu(ui: &mut egui::Ui, current: Option<&str>, presets: &[BrushPreset], st: &mut BrushesPanelState, picks: &mut Vec) { let gear = named(icons::button(ui, "settings", 24.0, false, tl!("Brush Preset Options")), "Brush Preset Options"); // The menu hangs 30 pt right of the gear, off the button's own edge; the align fallbacks still @@ -400,40 +536,61 @@ fn gear_menu(ui: &mut egui::Ui, current: Option<&str>, presets: &[BrushPreset], other => other, }; egui::Popup::menu(&gear).anchor(anchor).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - if ui.button(tl!("New Brush Preset…")).clicked() { - picks.push(Pick::NewPreset); - ui.close(); - } - ui.separator(); let current = current.filter(|n| presets.iter().any(|p| p.name.eq_ignore_ascii_case(n))).map(str::to_string); - ui.add_enabled_ui(current.is_some(), |ui| { - if ui.button(tl!("Rename Brush…")).clicked() - && let Some(name) = current.clone() - { - st.renaming = Some(Renaming { group: false, name, folder: Vec::new(), text: String::new() }); - ui.close(); - } - if ui.button(tl!("Delete Brush")).clicked() - && let Some(name) = current.clone() - { - picks.push(Pick::List(Action::Delete(name))); - ui.close(); - } - }); - ui.separator(); // What a preset's card shows: a checkbox per part. At least one stays on — clicking the - // last checked box does nothing, since an empty card would show no brush at all. - let on = [st.show_name, st.show_stroke, st.show_tip].into_iter().filter(|b| *b).count(); - for (flag, label) in [(&mut st.show_name, tl!("Brush Name")), (&mut st.show_stroke, tl!("Brush Stroke")), (&mut st.show_tip, tl!("Brush Tip"))] { - let was = *flag; - if ui.checkbox(flag, label).changed() && was && on == 1 { - *flag = true; + // last checked box does nothing, since an empty card would show no brush at all. Counted + // before each box, so two clicks in one frame cannot turn off the last two parts. + for item in GEAR_MENU { + let Some(item) = *item else { + ui.separator(); + continue; + }; + let label = tl!(item.label()); + match item { + Gear::Name | Gear::Stroke | Gear::Tip => { + let on = [st.show_name, st.show_stroke, st.show_tip].into_iter().filter(|b| *b).count(); + let flag = match item { + Gear::Name => &mut st.show_name, + Gear::Stroke => &mut st.show_stroke, + _ => &mut st.show_tip, + }; + let was = *flag; + if ui.checkbox(flag, label).changed() && was && on == 1 { + *flag = true; + } + } + Gear::SearchBar => { + ui.checkbox(&mut st.show_search, label); + } + // Checked by default in Photoshop; greyed until their function lands. + Gear::AdditionalInfo | Gear::RecentBrushes => { + ui.add_enabled(false, egui::Checkbox::new(&mut true, label)); + } + _ => { + let enabled = !item.placeholder() && (!item.needs_preset() || current.is_some()); + if !ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + continue; + } + match (item, current.clone()) { + (Gear::NewPreset, _) => picks.push(Pick::NewPreset), + (Gear::Import, _) => picks.push(Pick::Import), + (Gear::Rename, Some(name)) => { + st.renaming = Some(Renaming { group: false, name, folder: Vec::new(), text: String::new() }); + } + (Gear::Delete, Some(name)) => picks.push(Pick::List(Action::Delete(name))), + _ => {} + } + ui.close(); + } } } - ui.separator(); - if ui.button(tl!("Import Brushes…")).clicked() { - picks.push(Pick::Import); - ui.close(); - } }); } + +#[cfg(test)] +#[path = "../brush_picker_gear_menu_tests.rs"] +mod gear_menu_tests; + +#[cfg(test)] +#[path = "../brush_picker_angle_widget_tests.rs"] +mod brush_picker_angle_widget_tests; diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs new file mode 100644 index 0000000000..c1919c8639 --- /dev/null +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -0,0 +1,55 @@ +//! Photoshop's alerts when a painting tool can't paint (#11898): a press on a hidden target +//! layer, on a layer with Lock All, or with a group active (its pixels, not its mask) opens a +//! modal alert with OK instead of a status-bar message, and paints nothing. Only the tools whose +//! wording was measured have a name here ([`tool_name`]); the others keep today's status bar. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +/// The alerts; `{tool}` is [`tool_name`]. +pub const HIDDEN: &str = "Could not use the {tool} because the target layer is hidden."; +pub const LOCKED: &str = "Could not use the {tool} because the layer is locked."; +pub const GROUP: &str = "Could not use the {tool} because the pixels in a group cannot be edited without merging the group."; + +/// The tool's name in the alerts, for the tools whose wording was measured: the Brush. +pub fn tool_name(tool: Tool) -> Option<&'static str> { + match tool { + Tool::Brush => Some(tl!("brush tool")), + _ => None, + } +} + +/// The alert a press with `tool` gets, if any. `hidden` is the press-time hidden-target refusal +/// (`canvas::tool_input`), which this only words; the lock and the group are checked here. Lock +/// transparent pixels is no refusal, and a group's targeted mask paints. +pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option { + let name = tool_name(tool)?; + let template = if hidden { + HIDDEN + } else { + let st = app.session.active()?; + let layer = st.active_layer.and_then(|id| st.doc.layer(id))?; + if crate::canvas::paint_target(app) != json!("pixels") { + return None; + } + if layer.is_group() { + GROUP + } else if st.doc.effective_locks(layer.id).all { + LOCKED + } else { + return None; + } + }; + Some(crate::i18n::fmt(tl!(template), &[("tool", name)])) +} + +/// Opens the alert: ordinary dialog state, listed by `ui.inspect` and closed by `ui.dialog.confirm`. +pub fn prompt(app: &mut PhotocraftApp, message: &str) { + app.ui.open_dialog(DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); +} + +#[cfg(test)] +#[path = "../brush_refusal_alert_tests.rs"] +mod brush_refusal_alert_tests; diff --git a/crates/ui-egui/src/tools/count_show_extras_tests.rs b/crates/ui-egui/src/tools/count_show_extras_tests.rs new file mode 100644 index 0000000000..773ce74546 --- /dev/null +++ b/crates/ui-egui/src/tools/count_show_extras_tests.rs @@ -0,0 +1,70 @@ +//! #11770: adding a count marker while View > Show > Count is off switches it back on. + +use egui::Modifiers; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.ui.tool = Tool::Count; + app +} + +fn click(app: &mut PhotocraftApp, x: f64, y: f64, m: Modifiers) { + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x, y }, m); +} + +fn points(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.measurement.count_groups.iter().map(|g| g.points.len()).sum() +} + +fn past(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +#[test] +fn a_click_with_show_count_off_adds_the_marker_and_turns_it_on() { + let mut app = app(); + app.ui.view.show.count = false; + let before = past(&app); + click(&mut app, 40.0, 30.0, Modifiers::NONE); + assert_eq!(points(&app), 1); + assert!(app.ui.view.show.count, "the new marker is visible"); + assert_eq!(past(&app), before + 1, "only the marker's own history state"); +} + +#[test] +fn a_click_with_show_count_on_behaves_as_before() { + let mut app = app(); + app.ui.view.show.count = true; + click(&mut app, 40.0, 30.0, Modifiers::NONE); + assert_eq!(points(&app), 1); + assert!(app.ui.view.show.count); +} + +#[test] +fn a_click_into_a_hidden_group_leaves_the_group_hidden() { + let mut app = app(); + click(&mut app, 10.0, 10.0, Modifiers::NONE); + app.run("count.setGroup", json!({"group": 0, "visible": false})).unwrap(); + app.ui.view.show.count = false; + click(&mut app, 90.0, 60.0, Modifiers::NONE); + assert_eq!(points(&app), 2); + assert!(app.ui.view.show.count); + assert!(!app.session.active().unwrap().doc.measurement.count_groups[0].visible); +} + +#[test] +fn removing_a_marker_does_not_turn_show_count_on() { + let mut app = app(); + click(&mut app, 10.0, 10.0, Modifiers::NONE); + app.ui.view.show.count = false; + click(&mut app, 10.0, 10.0, Modifiers::ALT); + assert_eq!(points(&app), 0); + assert!(!app.ui.view.show.count); +} diff --git a/crates/ui-egui/src/tools/crop_presets.rs b/crates/ui-egui/src/tools/crop_presets.rs index a68f577425..9cd6622b4c 100644 --- a/crates/ui-egui/src/tools/crop_presets.rs +++ b/crates/ui-egui/src/tools/crop_presets.rs @@ -157,36 +157,35 @@ pub fn dropdown(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let can_new = savable(o).is_some(); let mut chosen: Option = None; let parent_layer = ui.layer_id(); - let combo = - craft_ui::ComboBox::from_id_salt("crop-ratio").selected_text(label).width(140.0).height(420.0).icon(crate::widgets::chevron_icon).show_ui(ui, |ui| { - crate::press_menu::above_parent_ui(parent_layer, ui); - if selection_entry && ui.selectable_label(true, tl!("Selection")).clicked() { - chosen = Some(Choice::Selection); + let combo = crate::widgets::combo_list(ui, "crop-ratio", label, 140.0, egui::PopupCloseBehavior::CloseOnClick, |ui| { + crate::press_menu::above_parent_ui(parent_layer, ui); + if selection_entry && ui.selectable_label(true, tl!("Selection")).clicked() { + chosen = Some(Choice::Selection); + } + let (before, after): (Vec<_>, Vec<_>) = builtin.iter().partition(|(k, _)| k != crop_size::FRONT); + for (k, l) in &before { + if ui.selectable_label(!selection_entry && current_user.is_none() && *k == o.crop_ratio, tl!(l)).clicked() { + chosen = Some(Choice::Builtin(k.clone())); } - let (before, after): (Vec<_>, Vec<_>) = builtin.iter().partition(|(k, _)| k != crop_size::FRONT); - for (k, l) in &before { - if ui.selectable_label(!selection_entry && current_user.is_none() && *k == o.crop_ratio, tl!(l)).clicked() { - chosen = Some(Choice::Builtin(k.clone())); - } + } + for (name, _) in &users { + if ui.selectable_label(!selection_entry && current_user.as_deref() == Some(name), name.as_str()).clicked() { + chosen = Some(Choice::User(name.clone())); } - for (name, _) in &users { - if ui.selectable_label(!selection_entry && current_user.as_deref() == Some(name), name.as_str()).clicked() { - chosen = Some(Choice::User(name.clone())); - } + } + for (k, l) in &after { + if ui.selectable_label(false, tl!(l)).clicked() { + chosen = Some(Choice::Builtin(k.clone())); } - for (k, l) in &after { - if ui.selectable_label(false, tl!(l)).clicked() { - chosen = Some(Choice::Builtin(k.clone())); - } - } - ui.separator(); - if ui.add_enabled(can_new, egui::Button::selectable(false, tl!("New Crop Preset…"))).clicked() { - chosen = Some(Choice::New); - } - if ui.add_enabled(!users.is_empty(), egui::Button::selectable(false, tl!("Delete Crop Preset…"))).clicked() { - chosen = Some(Choice::Delete); - } - }); + } + ui.separator(); + if ui.add_enabled(can_new, egui::Button::selectable(false, tl!("New Crop Preset…"))).clicked() { + chosen = Some(Choice::New); + } + if ui.add_enabled(!users.is_empty(), egui::Button::selectable(false, tl!("Delete Crop Preset…"))).clicked() { + chosen = Some(Choice::Delete); + } + }); let _ = combo.response.accessible_name(tl!("Aspect Ratio")); if let Some(c) = chosen { apply_choice(app, c); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 3c5b997cb3..057a1442e3 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -90,6 +90,49 @@ fn opt(ui: &mut egui::Ui, text: &str) { crate::widgets::scrub_option_label(ui, &label); } +/// The reference application's alert for a Background Eraser Angle typed outside −180…180. +pub(crate) const ANGLE_RANGE_MESSAGE: &str = "An integer between -180 ° and 180 ° is required. Closest value inserted."; + +/// The Background Eraser's Angle: an angle icon and a whole-degree field on the brush tip's +/// angle, −180…180, default 0. Returns true when a typed value was out of range and was clamped +/// (400 → 180): the caller shows [`ANGLE_RANGE_MESSAGE`] once the entry is committed. +fn angle_field(ui: &mut egui::Ui, b: &mut photocraft_engine::BrushSettings) -> bool { + let t = Tokens::get(ui.ctx()); + let tip = tl!("Set the brush angle"); + ui.add(icons::image("rotate-cw", 15.0, t.text_dim)).on_hover_text(tip); + // A wider range than the angle's, so a typed 400 reaches us and can be told apart from 180. + let mut a = b.angle; + // Read before the field: it consumes the arrow keys it steps with, and the wheel it steps + // with while focused never shows in the scroll delta (a view's scroll does, and is no step). + let arrow_or_wheel = + ui.input(|i| i.key_pressed(egui::Key::ArrowUp) || i.key_pressed(egui::Key::ArrowDown)) || crate::field_wheel::focused_field_wheeled(ui.ctx()); + let r = widgets::value_field_named(ui, tl!("Angle"), &mut a, -ANGLE_TYPED_MAX..=ANGLE_TYPED_MAX, "°", 52.0); + let out_of_range = r.id.with("bg-eraser-angle-out-of-range"); + // The flag lives only while an entry is being typed: drawn without the keyboard, the field + // drops it, so an entry the tool switch cut off (never committed) can't alert on a later one. + // The widget's own focus, not `has_focus()`: that is false while the window is in the + // background, and switching away mid-entry must keep the alert for the commit. + if !ui.memory(|m| m.has_focus(r.id)) && !r.lost_focus() { + ui.data_mut(|d| d.remove_temp::(out_of_range)); + } + if r.changed() && a.is_finite() { + let whole = a.trunc(); + let clamped = whole.clamp(-180.0, 180.0); + b.angle = clamped; + // Only typing alerts: a scrub or an arrow-key step past the end just stops there. + let stepped = r.dragged() || arrow_or_wheel; + // A wheel step over the field without its focus is no entry either. + let typed_out = whole != clamped && !stepped && (r.has_focus() || r.lost_focus()); + ui.data_mut(|d| d.insert_temp(out_of_range, typed_out)); + } + let r = r.on_hover_text(tip); + // Enter (or a click away) commits the entry: the alert comes then, not mid-typing. + r.lost_focus() && ui.data_mut(|d| d.remove_temp::(out_of_range)).unwrap_or(false) +} + +/// How far the Angle field lets a typed number through before [`angle_field`] clamps it. +const ANGLE_TYPED_MAX: f32 = 1.0e6; + /// Options bar for the Magic Eraser and Background Eraser. Returns false for other tools. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { let o = &mut app.ui.tool_options; @@ -133,8 +176,22 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo if tolerance_field(ui, &mut o.bg_tolerance) { open_range_alert(app); } - let o = &mut app.ui.tool_options; - widgets::checkbox(ui, &mut o.bg_protect_fg, tl!("Protect Foreground Color")).on_hover_text(tl!("Do not erase the foreground swatch color")); + // Angle and Pressure for Size edit the tool's own brush (the shell swaps one in per + // tool), through `tools.setBrush` like the Brush Settings panel. + let before = app.session.tools.brush.clone(); + let mut brush = before.clone(); + if angle_field(ui, &mut brush) { + let message = tl!(ANGLE_RANGE_MESSAGE).to_string(); + app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } + widgets::checkbox(ui, &mut app.ui.tool_options.bg_protect_fg, tl!("Protect Foreground Color")) + .on_hover_text(tl!("Do not erase the foreground swatch color")); + let name = tl!("Always use pressure for size"); + let pressure = icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), brush.pressure_size, name, false); + if pressure.on_hover_text(tl!("Always use Pressure for Size. When off, Brush Preset controls pressure")).clicked() { + brush.pressure_size = !brush.pressure_size; + } + crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); } _ => return false, } diff --git a/crates/ui-egui/src/tools/gradient_ui.rs b/crates/ui-egui/src/tools/gradient_ui.rs index c3d64441c9..34373d66b6 100644 --- a/crates/ui-egui/src/tools/gradient_ui.rs +++ b/crates/ui-egui/src/tools/gradient_ui.rs @@ -890,7 +890,10 @@ fn selection_after_edit(f: &Fill, p: &Value, previous: Option) -> Option } fn stop_strip(ui: &mut egui::Ui, key: egui::Id, f: &Fill, midpoints: bool, pending: Option<&Value>, colors: ([f32; 4], [f32; 4])) -> Option { - let Fill::Gradient { stops, .. } = f else { return None }; + // The stops as committed: a drag edit (and the two-stop minimum) addresses these, not the + // pending preview, which may already leave the dragged stop out. + let Fill::Gradient { stops, opacity_stops, .. } = f else { return None }; + let opacity_count = if opacity_stops.is_empty() { 2 } else { opacity_stops.len() }; let t = Tokens::get(ui.ctx()); let w = ui.available_width().max(120.0); let (outer, resp) = ui.allocate_exact_size(vec2(w, 58.0), Sense::click_and_drag()); @@ -995,19 +998,22 @@ fn stop_strip(ui: &mut egui::Ui, key: egui::Id, f: &Fill, midpoints: bool, pendi let dragging: Option = ui.data(|d| d.get_temp(key)); let mut preview = None; if let (Some(m), Some(pos)) = (dragging, resp.interact_pointer_pos()) { - let off = if off_strip(pos, bar) { 1.0 } else { 0.0 }; + // Pulled off the bar, up or down, the stop is deleted (the preview shows it gone; + // dragging back cancels), while at least two of its kind remain. + let off = off_strip(pos, bar); let loc = loc_of(pos.x); let edit = match m { - Marker::Color(i) if off > 0.0 && stops.len() > 2 => json!({"action": "delete", "index": i}), + Marker::Color(i) if off && stops.len() > 2 => json!({"action": "delete", "index": i}), Marker::Color(i) => json!({"action": "move", "index": i, "location": loc}), - Marker::Opacity(i) if off > 0.0 && ops.len() > 2 => json!({"action": "delete", "kind": "opacity", "index": i}), + Marker::Opacity(i) if off && opacity_count > 2 => json!({"action": "delete", "kind": "opacity", "index": i}), Marker::Opacity(i) => json!({"action": "move", "kind": "opacity", "index": i, "location": loc}), Marker::Mid(i) => { let (a, b) = (sorted.get(i).map_or(0.0, |s| s.0), sorted.get(i + 1).map_or(1.0, |s| s.0)); json!({"action": "midpoint", "index": i, "location": ((loc - a) / (b - a).max(1e-4)).clamp(0.05, 0.95)}) } }; - if resp.dragged() { + // The release frame counts too: its own last move decides whether the stop comes off. + if resp.dragged() || resp.drag_stopped() { preview = Some(edit); } } diff --git a/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs b/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs index 8bc5019ddf..0882a50ed2 100644 --- a/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs +++ b/crates/ui-egui/src/tools/gradient_ui/editor_tests.rs @@ -144,3 +144,190 @@ fn preset_editor_opacity_fields_do_not_edit_document_history() { assert_eq!(h.state().session.active().unwrap().doc, before); assert_eq!(h.state().session.active().unwrap().history.past_len(), history); } + +/// Press at `points[0]`, move through the rest, then release at the last one; `during` runs while +/// the button is still down at the last point. +fn drag_through(h: &mut Harness, points: &[Pos2], during: impl FnOnce(&mut Harness)) { + let (Some(&from), Some(&to)) = (points.first(), points.last()) else { return }; + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + for &p in &points[1..] { + // Two small steps per leg, as a real pointer reports. + let last = h.ctx.input(|i| i.pointer.latest_pos()).unwrap_or(p); + h.event(egui::Event::PointerMoved(last + (p - last) * 0.5)); + h.run_steps(1); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + } + during(h); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); +} + +/// A stop marker's centre on the strip: colour stops under the bar, opacity stops above it. +fn marker(h: &Harness, location: f32, opacity: bool) -> Pos2 { + let rect = h.get_by_label("Gradient stops").rect(); + pos2(rect.left() + 8.0 + location * (rect.width() - 16.0), rect.top() + if opacity { 6.0 } else { 50.0 }) +} + +fn counts(h: &Harness, sink: Sink) -> (usize, usize) { + let Fill::Gradient { stops, opacity_stops, .. } = sink.fill(h.state()).unwrap() else { panic!() }; + (stops.len(), opacity_stops.len()) +} + +/// The strip as drawn while the pointer is down: the pending edit applied to the gradient. +fn shown(h: &Harness, sink: Sink) -> (usize, usize) { + let f = sink.fill(h.state()).unwrap(); + let pending = match sink { + Sink::Layer(_) => h.state().gradient.panel.as_ref().map(|(.., p)| p.clone()), + Sink::Preset => h.state().gradient.preset_stop.clone(), + }; + let (fg, bg) = (h.state().session.tools.foreground, h.state().session.tools.background); + let f = pending.and_then(|p| cmds::apply_stop(&f, &p, fg, bg).ok()).unwrap_or(f); + let Fill::Gradient { stops, opacity_stops, .. } = f else { panic!() }; + (stops.len(), opacity_stops.len()) +} + +/// #10742: a colour stop dragged down off the bar (by about a marker's height) is removed on +/// release; while it is off the bar the strip already shows it gone; one undo step restores it. +#[test] +fn a_color_stop_dragged_down_off_the_bar_is_removed() { + for layer in [true, false] { + let (mut h, sink) = editor(layer); + let history = h.state().session.active().unwrap().history.past_len(); + let before = sink.fill(h.state()).unwrap(); + let from = marker(&h, 0.5, false); + drag_through(&mut h, &[from, from + vec2(0.0, 22.0)], |h| { + assert_eq!(shown(h, sink), (2, 3), "layer {layer}: the dragged-off stop is gone from the preview"); + assert_eq!(sink.fill(h.state()).unwrap(), before, "layer {layer}: nothing is committed before release"); + }); + let Fill::Gradient { stops, .. } = sink.fill(h.state()).unwrap() else { panic!() }; + assert_eq!(stops.iter().map(|s| s.0).collect::>(), [0.0, 1.0], "layer {layer}: the middle stop is removed"); + assert_eq!(counts(&h, sink), (2, 3), "layer {layer}: opacity stops are untouched"); + if layer { + assert_eq!(h.state().session.active().unwrap().history.past_len(), history + 1, "one undo step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(sink.fill(h.state()).unwrap(), before); + } + } +} + +/// Dragging a stop off the bar and back onto it before releasing cancels the removal. +#[test] +fn dragging_a_stop_back_onto_the_bar_cancels_the_removal() { + for layer in [true, false] { + let (mut h, sink) = editor(layer); + for opacity in [false, true] { + let from = marker(&h, 0.5, opacity); + let away = from + vec2(0.0, if opacity { -30.0 } else { 30.0 }); + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(from + (away - from) * 0.5)); + h.run_steps(1); + h.event(egui::Event::PointerMoved(away)); + h.run_steps(1); + assert_eq!(shown(&h, sink), if opacity { (3, 2) } else { (2, 3) }, "layer {layer}: off the bar the stop is gone"); + // Back on the bar before release: the stop returns and stays where it was. + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + assert_eq!(shown(&h, sink), (3, 3), "layer {layer}: back on the bar, the stop is shown"); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); + let Fill::Gradient { stops, opacity_stops, .. } = sink.fill(h.state()).unwrap() else { panic!() }; + let locations: Vec = if opacity { opacity_stops.iter().map(|s| s.0).collect() } else { stops.iter().map(|s| s.0).collect() }; + assert_eq!((stops.len(), opacity_stops.len()), (3, 3), "layer {layer} opacity {opacity}: nothing removed"); + assert!((locations[1] - 0.5).abs() < 1e-3, "layer {layer} opacity {opacity}: {locations:?}"); + } + } +} + +/// The last two colour stops stay: dragging one off the bar leaves it where it is. +#[test] +fn the_last_two_color_stops_cannot_be_dragged_off() { + let (mut h, sink) = editor(true); + let from = marker(&h, 0.5, false); + drag_through(&mut h, &[from, from + vec2(0.0, 60.0)], |_| {}); + assert_eq!(counts(&h, sink), (2, 3)); + let after = sink.fill(h.state()).unwrap(); + for location in [0.0, 1.0] { + let from = marker(&h, location, false); + drag_through(&mut h, &[from, from + vec2(0.0, 60.0)], |h| assert_eq!(shown(h, sink).0, 2, "the preview keeps two stops")); + assert_eq!(sink.fill(h.state()).unwrap(), after, "two colour stops always remain"); + } +} + +/// An opacity stop dragged up off the bar is removed while two remain. +#[test] +fn an_opacity_stop_dragged_up_off_the_bar_is_removed() { + for layer in [true, false] { + let (mut h, sink) = editor(layer); + let from = marker(&h, 0.5, true); + drag_through(&mut h, &[from, from - vec2(0.0, 30.0)], |h| assert_eq!(shown(h, sink), (3, 2), "layer {layer}")); + let Fill::Gradient { opacity_stops, stops, .. } = sink.fill(h.state()).unwrap() else { panic!() }; + assert_eq!(opacity_stops.iter().map(|s| s.0).collect::>(), [0.0, 1.0], "layer {layer}"); + assert_eq!(stops.len(), 3, "layer {layer}: colour stops are untouched"); + // Two opacity stops remain: the next one dragged up stays. + let before = sink.fill(h.state()).unwrap(); + let from = marker(&h, 0.0, true); + drag_through(&mut h, &[from, from - vec2(0.0, 30.0)], |_| {}); + assert_eq!(sink.fill(h.state()).unwrap(), before, "layer {layer}: two opacity stops always remain"); + } +} + +/// Either way off the bar takes a stop off, as in the reference application: an opacity stop +/// dragged down past the colour stops and a colour stop dragged up past the opacity stops are +/// removed too. +#[test] +fn a_stop_dragged_the_other_way_comes_off_too() { + for layer in [true, false] { + for opacity in [true, false] { + let (mut h, sink) = editor(layer); + let from = marker(&h, 0.5, opacity); + let to = from + vec2(0.0, if opacity { 70.0 } else { -70.0 }); + let gone = if opacity { (3, 2) } else { (2, 3) }; + drag_through(&mut h, &[from, to], |h| assert_eq!(shown(h, sink), gone, "layer {layer} opacity {opacity}: gone from the preview")); + assert_eq!(counts(&h, sink), gone, "layer {layer} opacity {opacity}: the stop is removed"); + } + } +} + +/// Press on a stop, drag a little along the bar, then move to each of `then` in its own frame; +/// the last move and the release arrive in the same frame, as a quick flick does. +fn flick(h: &mut Harness, from: Pos2, then: &[Pos2]) { + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(from + vec2(10.0, 0.0))); + h.run_steps(1); + let Some((&last, moves)) = then.split_last() else { return }; + for &p in moves { + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + } + // `Harness::event` runs one frame per event, so both go straight into the next frame. + let input = &mut h.input_mut().events; + input.push(egui::Event::PointerMoved(last)); + input.push(egui::Event::PointerButton { pos: last, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + h.run_steps(3); +} + +/// The release frame counts: a stop flicked off the bar and released in the same frame is +/// removed, and one brought back onto the bar in the release frame is kept. +#[test] +fn the_release_frame_decides_whether_the_stop_comes_off() { + for layer in [true, false] { + let (mut h, sink) = editor(layer); + let from = marker(&h, 0.5, false); + let away = from + vec2(10.0, 40.0); + flick(&mut h, from, &[away, from]); + assert_eq!(counts(&h, sink), (3, 3), "layer {layer}: back on the bar at release, the stop is kept"); + let from = marker(&h, 0.5, false); + flick(&mut h, from, &[from + vec2(10.0, 40.0)]); + assert_eq!(counts(&h, sink), (2, 3), "layer {layer}: released off the bar in the same frame, the stop is removed"); + } +} diff --git a/crates/ui-egui/src/tools/lasso_ui/tests.rs b/crates/ui-egui/src/tools/lasso_ui/tests.rs index 816d661152..a568d102ae 100644 --- a/crates/ui-egui/src/tools/lasso_ui/tests.rs +++ b/crates/ui-egui/src/tools/lasso_ui/tests.rs @@ -524,3 +524,39 @@ fn alt_clicking_narrow_and_rotated_polygons_keeps_the_fourth_corner() { assert!(app.session.active().unwrap().doc.selection.is_some()); } } + +/// #9841: the Lasso reads its own raw pointer events (`lasso_ui::canvas_input`), so the +/// `Buttons` starvation the other tools get does not reach it. A press that dismisses the +/// canvas tool menu must not draw a Lasso selection, and the next ordinary drag must work. +#[test] +fn a_menu_dismissal_press_never_draws_a_lasso_selection() { + let mut h = harness(); + // Right-click on the canvas: the selection menu opens. + let menu_at = crate::canvas::ViewXform::active(h.state()).unwrap().to_screen(300.0, 100.0); + h.event(Event::PointerMoved(menu_at)); + h.run_steps(1); + h.event(Event::PointerButton { pos: menu_at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerButton { pos: menu_at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_some(), "right-click opens the selection menu"); + let revision = h.state().session.active().unwrap().revision; + // The dismissal press and drag, well clear of the menu. + mouse(&mut h, "down", 50.0, 250.0, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_none(), "the outside press dismisses the menu"); + mouse(&mut h, "move", 50.0, 200.0, Modifiers::NONE); + mouse(&mut h, "move", 150.0, 200.0, Modifiers::NONE); + mouse(&mut h, "move", 150.0, 250.0, Modifiers::NONE); + mouse(&mut h, "up", 150.0, 250.0, Modifiers::NONE); + h.run_steps(2); + assert!(h.state().drag.is_none(), "the consumed gesture must not leave a Lasso drag behind"); + assert!(h.state().session.active().unwrap().doc.selection.is_none(), "the consumed gesture must draw no selection"); + assert_eq!(h.state().session.active().unwrap().revision, revision, "and no history step"); + // The next ordinary drag draws one, so the guard did not stick. + mouse(&mut h, "down", 50.0, 50.0, Modifiers::NONE); + mouse(&mut h, "move", 90.0, 40.0, Modifiers::NONE); + mouse(&mut h, "move", 150.0, 60.0, Modifiers::NONE); + mouse(&mut h, "up", 150.0, 60.0, Modifiers::NONE); + h.run_steps(2); + assert!(h.state().session.active().unwrap().doc.selection.is_some(), "an ordinary Lasso drag draws again"); +} diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs index f669f61368..d7884b3799 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui.rs @@ -483,16 +483,23 @@ pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, hover: } } -/// The cursor over the canvas: a crosshair; Preferences › Cursors › Other Cursors › Precise also -/// shows the detection width around it. +/// The cursor over the canvas: the tool's icon with its top-left tip on the point; Preferences › +/// Cursors › Other Cursors › Precise shows the detection width around a crosshair instead, and +/// Caps Lock swaps the preference either way, as in Photoshop (#11690). pub fn cursor(app: &PhotocraftApp, painter: &egui::Painter, p: Pos2, zoom: f32) -> egui::CursorIcon { - if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { - let r = (app.ui.tool_options.magnetic_width.clamp(1.0, 256.0) * zoom).max(2.0); - painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140))); - painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220))); + if !crate::canvas::precise_other_cursor(app) { + // The icon's lasso tip is at (1.8, 3.6) of its 24-unit box. + crate::icons::cursor(painter.ctx(), crate::icons::tool_icon(Tool::MagneticLasso), p, vec2(1.8, 3.6) / 24.0, 22.0); + return egui::CursorIcon::None; } + let r = (app.ui.tool_options.magnetic_width.clamp(1.0, 256.0) * zoom).max(2.0); + painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140))); + painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220))); egui::CursorIcon::Crosshair } #[cfg(test)] mod tests; + +#[cfg(test)] +mod caps_lock_cursor_tests; diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs new file mode 100644 index 0000000000..297a71b174 --- /dev/null +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui/caps_lock_cursor_tests.rs @@ -0,0 +1,74 @@ +//! Caps Lock and the Magnetic Lasso's cursor (#11690): it swaps Preferences › Cursors › Other +//! Cursors, so with Standard and Caps Lock on the pointer shows a circle as big as the detection +//! Width (scaled with zoom), and with Precise and Caps Lock on it is the tool's icon, as with +//! Standard alone. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +fn app(other: &str, caps_lock: bool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.ui.tool = Tool::MagneticLasso; + app.ui.tool_options.magnetic_width = 10.0; + app.run("prefs.set", json!({"path": "cursors.other", "value": other})).unwrap(); + app.caps_lock = caps_lock; + app +} + +/// The radii of the circles `cursor` draws at `zoom`, and the OS cursor it asks for. +fn drawn(app: &PhotocraftApp, zoom: f32) -> (Vec, egui::CursorIcon) { + let (radii, icon, _) = drawn_with_others(app, zoom); + (radii, icon) +} + +/// As [`drawn`], plus how many shapes that are not circles it draws (the icon). +fn drawn_with_others(app: &PhotocraftApp, zoom: f32) -> (Vec, egui::CursorIcon, usize) { + let ctx = egui::Context::default(); + ctx.begin_pass(egui::RawInput::default()); + let painter = ctx.layer_painter(egui::LayerId::background()); + let icon = super::cursor(app, &painter, egui::pos2(100.0, 100.0), zoom); + let mut out = ctx.end_pass(); + out.textures_delta.clear(); + let radii: Vec = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Circle(c) => Some(c.radius), + _ => None, + }) + .collect(); + let others = out.shapes.len() - radii.len(); + (radii, icon, others) +} + +#[test] +fn caps_lock_on_standard_draws_the_width_circle_scaled_with_zoom() { + let app = app("standard", true); + let (radii, icon) = drawn(&app, 1.0); + assert!(radii.iter().any(|r| (r - 10.0).abs() < 1e-3), "a 10 px circle at Width 10, 100 %: {radii:?}"); + assert_eq!(icon, egui::CursorIcon::Crosshair, "with a crosshair in the middle"); + let (radii, _) = drawn(&app, 2.0); + assert!(radii.iter().any(|r| (r - 20.0).abs() < 1e-3), "twice as big at 200 %: {radii:?}"); +} + +#[test] +fn caps_lock_on_precise_swaps_back_to_the_tool_icon() { + let (radii, icon, others) = drawn_with_others(&app("precise", true), 1.0); + assert!(radii.is_empty(), "no width circle: {radii:?}"); + assert_eq!(icon, egui::CursorIcon::None, "the OS cursor hides behind the icon"); + assert!(others > 0, "the tool icon is drawn"); +} + +#[test] +fn without_caps_lock_the_preference_decides() { + let (radii, icon, others) = drawn_with_others(&app("standard", false), 1.0); + assert!(radii.is_empty(), "Standard: no circle"); + assert_eq!(icon, egui::CursorIcon::None, "Standard: the tool icon, not a crosshair"); + assert!(others > 0, "Standard: the tool icon is drawn"); + let (radii, icon) = drawn(&app("precise", false), 1.0); + assert!(!radii.is_empty(), "Precise: the width circle"); + assert_eq!(icon, egui::CursorIcon::Crosshair, "Precise: with the crosshair"); +} diff --git a/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs b/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs index b5e41a5e1b..db059edc3c 100644 --- a/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs +++ b/crates/ui-egui/src/tools/magnetic_lasso_ui/tests.rs @@ -418,6 +418,44 @@ fn on_the_canvas_the_border_follows_the_hovering_pointer_and_keys_work() { assert!((area - 5600.0).abs() < 120.0, "{area}"); } +/// #9841: the hover moves are a pointer-only gesture. Two things must hold: they keep running on +/// frames with no button event at all (the freeze the main-merge regression reintroduced), and a +/// consumed menu-dismissal gesture must not track the pointer. +/// +/// A canvas menu cannot be open over a live border — `canvas_tool_menu::magnetic_drawing` refuses +/// one for a Magnetic Lasso border in progress (#11689), on the canvas and through the control +/// channel alike — so the `menu_dismiss_press` check on the hover block is a guard rather than a +/// sequence a pointer can reach. The dismissal state is staged directly here, with the button held +/// as the real gesture has it: the flag is scoped to a held button (a frame with every button up +/// clears it), so a pointer-up frame would clear it before the gate reads it and test nothing. +#[test] +fn on_the_canvas_hover_moves_survive_a_menu_dismissal_and_resume() { + let mut h = harness(); + ui_click(&mut h, 52.0, 37.0); + assert!(h.state().ui.magnetic.active()); + h.run_steps(2); + // Button up: the border follows the pointer with no button event at all. + ui_hover(&mut h, &[[52.0, 37.0], [100.0, 36.0]]); + let m = &h.state().ui.magnetic; + let end = m.live.last().or(m.path.last()).copied().unwrap(); + assert!((end[0] - 100.0).abs() < 1.5 && (end[1] - 40.0).abs() < 0.01, "hover tracks with the button up: {end:?}"); + // A consumed dismissal gesture with its button still down: the hover must not advance. + let far = screen(&h, 150.0, 130.0); + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.state_mut().ui.canvas_tool_menu_dismissed = true; + let held = h.state().ui.magnetic.clone(); + ui_hover(&mut h, &[[100.0, 36.0], [130.0, 36.0]]); + assert_eq!(h.state().ui.magnetic, held, "a consumed dismissal gesture must not track the pointer"); + // Released: the very next pointer move tracks again. + h.event(egui::Event::PointerButton { pos: far, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + ui_hover(&mut h, &[[130.0, 36.0], [120.0, 36.0]]); + let m = &h.state().ui.magnetic; + let end = m.live.last().or(m.path.last()).copied().unwrap(); + assert!((end[0] - 120.0).abs() < 1.5 && (end[1] - 40.0).abs() < 0.01, "hover resumes once released: {end:?}"); +} + #[test] fn on_the_canvas_a_double_click_closes_the_border() { let mut h = harness(); diff --git a/crates/ui-egui/src/tools/note_clear_all_tests.rs b/crates/ui-egui/src/tools/note_clear_all_tests.rs new file mode 100644 index 0000000000..5232d84d41 --- /dev/null +++ b/crates/ui-egui/src/tools/note_clear_all_tests.rs @@ -0,0 +1,203 @@ +//! #11791: the Note tool's Clear All asks "Are you sure you want to delete all notes?" first. OK +//! deletes every note in one "Delete all Notes" step that one undo restores; Cancel changes +//! nothing; `notes.delete {"all": true}` itself never asks. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::*; + +/// A 200 × 100 document with three notes, the second one selected, and the Note tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + for (x, author) in [(10, "A"), (60, "B"), (110, "C")] { + app.run("notes.add", json!({"x": x, "y": 20, "author": author})).unwrap(); + } + app.ui.tool = Tool::Note; + app.ui.analysis.note_selected = Some(1); + app +} + +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1200.0, 80.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + h +} + +fn notes(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.notes.len() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +/// The open Clear All alert's id. +fn alert(app: &PhotocraftApp) -> Option { + app.ui.dialogs.iter().find(|d| owns_clear_notes(&d.fields)).map(|d| d.id) +} + +/// Click the options bar's Clear All and return the alert it opened. +fn clear_all(h: &mut Harness<'static, PhotocraftApp>) -> u64 { + h.get_by_label("Clear All").click(); + h.run_steps(3); + alert(h.state()).expect("Clear All opens the alert") +} + +#[test] +fn clear_all_asks_first_and_cancel_changes_nothing() { + let mut h = harness(app()); + let before = steps(h.state()); + let id = clear_all(&mut h); + assert_eq!(notes(h.state()), 3, "nothing is deleted before the answer"); + let ctx = egui::Context::default(); + let mut texts = Vec::new(); + let mut o = ctx.run_ui(egui::RawInput::default(), clear_notes_body); + o.textures_delta.clear(); + for c in o.shapes { + if let egui::Shape::Text(t) = c.shape { + texts.push(t.galley.text().to_owned()); + } + } + assert!(texts.iter().any(|t| t == "Are you sure you want to delete all notes?"), "{texts:?}"); + crate::dialogs::cancel(h.state_mut(), id).unwrap(); + assert_eq!(notes(h.state()), 3); + assert_eq!(steps(h.state()), before, "no history step"); + assert_eq!(h.state().ui.analysis.note_selected, Some(1), "the selection stays"); +} + +#[test] +fn ok_deletes_every_note_in_one_step_that_undo_restores() { + let mut h = harness(app()); + let before = steps(h.state()); + let id = clear_all(&mut h); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); + let app = h.state(); + assert_eq!(notes(app), 0); + assert_eq!(steps(app), before + 1, "one history step"); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Delete all Notes")); + assert_eq!(app.ui.analysis.note_selected, None, "nothing selected after OK"); + assert!(h.get_by_label("Clear All").accesskit_node().is_disabled(), "Clear All greys without notes"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(notes(h.state()), 3, "one undo brings every note back"); +} + +#[test] +fn the_command_itself_never_asks_and_names_its_step_too() { + let mut app = app(); + app.run("notes.delete", json!({"all": true})).unwrap(); + assert_eq!(notes(&app), 0); + assert!(alert(&app).is_none(), "no alert from the command"); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Delete all Notes")); +} + +#[test] +fn clear_all_stays_grey_without_notes() { + let mut app = app(); + app.run("notes.delete", json!({"all": true})).unwrap(); + ask_clear_notes(&mut app); + assert!(alert(&app).is_none(), "nothing to ask about"); + let h = harness(app); + assert!(h.get_by_label("Clear All").accesskit_node().is_disabled()); +} + +#[test] +fn a_second_click_while_the_alert_is_open_opens_no_second_alert() { + let mut h = harness(app()); + clear_all(&mut h); + // The options bar alone, so nothing covers Clear All: the second click reaches the button. + h.get_by_label("Clear All").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialogs.iter().filter(|d| owns_clear_notes(&d.fields)).count(), 1); +} + +#[test] +fn ok_after_the_document_changed_deletes_nothing() { + let mut h = harness(app()); + let id = clear_all(&mut h); + let app = h.state_mut(); + app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); + app.run("notes.add", json!({"x": 5, "y": 5})).unwrap(); + let past: Vec = app.session.documents().iter().map(|d| d.history.past_len()).collect(); + assert!(crate::dialogs::confirm(app, id).is_err(), "the alert was for the first document"); + let docs = app.session.documents(); + assert_eq!(docs.iter().map(|d| d.doc.notes.len()).collect::>(), [3, 1], "no note deleted in either document"); + assert_eq!(docs.iter().map(|d| d.history.past_len()).collect::>(), past, "no history step in either"); +} + +/// The options bar with the open dialogs drawn over it, as the window shows them. +fn harness_with_dialogs(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1200.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + h +} + +#[test] +fn the_alert_shows_its_question_and_its_buttons_answer() { + for (button, left) in [("Cancel", 3), ("OK", 0)] { + let mut h = harness_with_dialogs(app()); + let before = steps(h.state()); + let id = clear_all(&mut h); + let d = h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap(); + assert_eq!(crate::dialogs::title(d), "Clear All"); + let question = egui_kittest::kittest::by().label("Are you sure you want to delete all notes?").include_labels(); + assert!(h.query_all(question).next().is_some(), "the question is shown"); + assert!(h.query_by_label("OK").is_some() && h.query_by_label("Cancel").is_some(), "OK and Cancel"); + h.get_by_label(button).click(); + h.run_steps(3); + assert!(alert(h.state()).is_none(), "{button} closes the alert"); + assert_eq!(notes(h.state()), left, "{button}: {left} notes left"); + assert_eq!(steps(h.state()), before + usize::from(left == 0), "{button}: history"); + } +} + +#[test] +fn enter_is_ok_and_escape_is_cancel() { + for (key, left) in [(egui::Key::Escape, 3), (egui::Key::Enter, 0)] { + let mut h = harness_with_dialogs(app()); + let before = steps(h.state()); + clear_all(&mut h); + h.key_press(key); + h.run_steps(3); + assert!(alert(h.state()).is_none(), "{key:?} closes the alert"); + assert_eq!(notes(h.state()), left, "{key:?}: {left} notes left"); + assert_eq!(steps(h.state()), before + usize::from(left == 0), "{key:?}: history"); + } +} + +#[test] +fn ok_brings_back_the_tool_defaults_in_the_options_bar() { + let mut app = app(); + app.run("notes.set", json!({"index": 1, "color": "#3366cc"})).unwrap(); + // Clicking the note shows its author and colour in the options bar (#7940). + show_note_options(&mut app, 1); + assert_eq!(app.ui.analysis.note_author, "B"); + let mut h = harness(app); + let id = clear_all(&mut h); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + let (defaults, a) = (AnalysisUi::default(), &h.state().ui.analysis); + assert_eq!((a.note_author.as_str(), a.note_color), (defaults.note_author.as_str(), defaults.note_color), "the tool defaults after OK"); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_bar_buttons_tests.rs b/crates/ui-egui/src/tools/perspective_crop_bar_buttons_tests.rs new file mode 100644 index 0000000000..01d4043b5e --- /dev/null +++ b/crates/ui-egui/src/tools/perspective_crop_bar_buttons_tests.rs @@ -0,0 +1,72 @@ +//! #11978: the Perspective Crop options bar shows its Cancel and Commit buttons only during a +//! session (a quad, or corners being clicked), and they still commit and cancel. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use super::*; + +const COMMIT: &str = "Commit current crop operation"; +const CANCEL: &str = "Cancel current crop operation"; + +/// A 200 × 150 document with the Perspective Crop tool chosen and no session. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.ui.tool = Tool::PerspectiveCrop; + app +} + +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1400.0, 80.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + h +} + +fn shows(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { + h.query_by_label_contains(label).is_some() +} + +#[test] +fn without_a_session_neither_button_shows() { + let h = harness(app()); + assert!(!shows(&h, COMMIT) && !shows(&h, CANCEL)); + assert!(h.query_by_label("Show Grid").is_some(), "the bar still ends with Show Grid"); +} + +#[test] +fn a_pending_quad_shows_both_and_commit_commits() { + let mut app = app(); + app.ui.perspective_crop = Some([[20.0, 20.0], [180.0, 20.0], [180.0, 130.0], [20.0, 130.0]]); + let mut h = harness(app); + assert!(shows(&h, COMMIT) && shows(&h, CANCEL)); + h.get_by_label_contains(COMMIT).click(); + h.run_steps(3); + let size = h.state().session.active().unwrap().doc.size; + assert_eq!((size.width, size.height), (160, 110), "Commit cropped to the quad"); + assert!(!shows(&h, COMMIT) && !shows(&h, CANCEL), "gone after commit"); +} + +#[test] +fn clicked_corners_show_both_and_cancel_cancels() { + let mut app = app(); + app.pcrop.clicks = vec![[20.0, 20.0], [180.0, 25.0]]; + let mut h = harness(app); + assert!(shows(&h, COMMIT) && shows(&h, CANCEL), "with clicked corners"); + h.get_by_label_contains(CANCEL).click(); + h.run_steps(3); + assert!(h.state().pcrop.clicks.is_empty(), "Cancel dropped the corners"); + assert_eq!(h.state().session.active().unwrap().doc.size.width, 200, "nothing cropped"); + assert!(!shows(&h, COMMIT) && !shows(&h, CANCEL), "gone after cancel"); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_modifiers_tests.rs b/crates/ui-egui/src/tools/perspective_crop_modifiers_tests.rs new file mode 100644 index 0000000000..1a95a885ad --- /dev/null +++ b/crates/ui-egui/src/tools/perspective_crop_modifiers_tests.rs @@ -0,0 +1,153 @@ +//! #11802: ⇧ and ⌥ constrain the Perspective Crop's new drag (a square, from the centre) and its +//! corner drags (one axis, stays a rectangle). Ctrl, and no modifier, keep today's behaviour. + +use egui::Modifiers; + +use super::*; + +const SHIFT: Modifiers = Modifiers::SHIFT; +const ALT: Modifiers = Modifiers::ALT; + +/// An 800 × 500 document with the Perspective Crop tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 500})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + app +} + +/// A press at `from`, a move and the release at `to`, all with `mods`. +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + assert!(pointer(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods)); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + assert!(pointer(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Up { x: to[0], y: to[1] }, mods)); +} + +fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Option<[[f64; 2]; 4]> { + Some([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]) +} + +#[test] +fn shift_drag_draws_a_square_of_the_shorter_side() { + let mut app = app(); + drag(&mut app, [100.0, 100.0], [522.0, 320.0], SHIFT); + assert_eq!(app.ui.perspective_crop, rect(100.0, 100.0, 320.0, 320.0), "422 x 220 drag: 220 x 220"); + // Up and to the left: anchored at the press, extending the drag's way. + app.ui.perspective_crop = None; + drag(&mut app, [500.0, 400.0], [450.0, 100.0], SHIFT); + assert_eq!(app.ui.perspective_crop, rect(450.0, 350.0, 500.0, 400.0)); +} + +#[test] +fn alt_drag_draws_from_the_centre() { + let mut app = app(); + drag(&mut app, [400.0, 250.0], [600.0, 350.0], ALT); + assert_eq!(app.ui.perspective_crop, rect(200.0, 150.0, 600.0, 350.0)); +} + +#[test] +fn shift_alt_drag_draws_a_centred_square() { + let mut app = app(); + drag(&mut app, [400.0, 250.0], [600.0, 350.0], SHIFT | ALT); + assert_eq!(app.ui.perspective_crop, rect(300.0, 150.0, 500.0, 350.0), "side twice the shorter drag side"); +} + +#[test] +fn the_live_box_follows_the_modifiers() { + let mut app = app(); + assert!(pointer(&mut app, ToolEvent::Down { x: 400.0, y: 250.0, pressure: 1.0 }, ALT)); + assert!(pointer(&mut app, ToolEvent::Move { x: 600.0, y: 350.0, pressure: 1.0 }, ALT)); + let Some(Drag::New { start, cur, square, centred }) = app.pcrop.drag else { panic!("drawing a box") }; + assert_eq!(new_box(start, cur, square, centred), rect(200.0, 150.0, 600.0, 350.0), "the overlay draws the centred box"); +} + +#[test] +fn shift_corner_drag_keeps_one_axis() { + let mut app = app(); + let q = [[100.0, 100.0], [500.0, 100.0], [500.0, 400.0], [100.0, 400.0]]; + // Mostly horizontal: only x moves. + app.ui.perspective_crop = Some(q); + drag(&mut app, [500.0, 400.0], [600.0, 430.0], SHIFT); + assert_eq!(app.ui.perspective_crop.unwrap()[2], [600.0, 400.0]); + // Mostly vertical: only y moves. + app.ui.perspective_crop = Some(q); + drag(&mut app, [500.0, 400.0], [520.0, 470.0], SHIFT); + assert_eq!(app.ui.perspective_crop.unwrap()[2], [500.0, 470.0]); + assert_eq!(app.ui.perspective_crop.unwrap()[..2], q[..2], "the other corners stay"); +} + +#[test] +fn alt_corner_drag_keeps_a_rectangle() { + let mut app = app(); + app.ui.perspective_crop = Some([[100.0, 100.0], [500.0, 100.0], [500.0, 400.0], [100.0, 400.0]]); + drag(&mut app, [500.0, 400.0], [740.0, 430.0], ALT); + assert_eq!(app.ui.perspective_crop, rect(100.0, 100.0, 740.0, 430.0), "opposite corner fixed, neighbours follow"); + // From the top-left corner too. + drag(&mut app, [100.0, 100.0], [50.0, 160.0], ALT); + assert_eq!(app.ui.perspective_crop, rect(50.0, 160.0, 740.0, 430.0)); +} + +#[test] +fn alt_corner_drag_on_a_skewed_quad_moves_the_corner_alone() { + // Not measured: today's single-corner drag. + let mut app = app(); + let q = [[100.0, 100.0], [500.0, 130.0], [480.0, 400.0], [120.0, 380.0]]; + app.ui.perspective_crop = Some(q); + drag(&mut app, q[2], [700.0, 450.0], ALT); + assert_eq!(app.ui.perspective_crop, Some([q[0], q[1], [700.0, 450.0], q[3]])); +} + +#[test] +fn no_modifier_and_ctrl_keep_todays_behaviour() { + for mods in [Modifiers::NONE, Modifiers::CTRL, Modifiers::COMMAND] { + let mut app = app(); + drag(&mut app, [100.0, 100.0], [522.0, 320.0], mods); + assert_eq!(app.ui.perspective_crop, rect(100.0, 100.0, 522.0, 320.0), "{mods:?}"); + drag(&mut app, [522.0, 320.0], [740.0, 430.0], mods); + assert_eq!(app.ui.perspective_crop, Some([[100.0, 100.0], [522.0, 100.0], [740.0, 430.0], [100.0, 320.0]]), "a single-corner drag"); + drag(&mut app, [300.0, 200.0], [310.0, 220.0], mods); + assert_eq!(app.ui.perspective_crop.unwrap()[0], [110.0, 120.0], "a press inside moves the quad"); + // Four clicks. + let mut app = self::app(); + for p in [[10.0, 10.0], [90.0, 12.0], [88.0, 70.0], [12.0, 72.0]] { + assert!(pointer(&mut app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, mods)); + assert!(pointer(&mut app, ToolEvent::Up { x: p[0], y: p[1] }, mods)); + } + assert_eq!(app.ui.perspective_crop, Some([[10.0, 10.0], [90.0, 12.0], [88.0, 70.0], [12.0, 72.0]])); + } +} + +#[test] +fn zero_size_drags_and_degenerate_quads_never_panic() { + for mods in [SHIFT, ALT, SHIFT | ALT, Modifiers::CTRL] { + let mut app = app(); + // A straight drag: no box. + drag(&mut app, [100.0, 100.0], [300.0, 100.0], mods); + assert_eq!(app.ui.perspective_crop, None, "{mods:?}"); + // All four corners on one point. + app.ui.perspective_crop = Some([[200.0, 200.0]; 4]); + drag(&mut app, [200.0, 200.0], [260.0, 230.0], mods); + // A quad with a line for a side. + app.ui.perspective_crop = Some([[100.0, 100.0], [100.0, 100.0], [400.0, 300.0], [100.0, 300.0]]); + drag(&mut app, [400.0, 300.0], [420.0, 360.0], mods); + assert!(new_box([1.0, 1.0], [1.0, 1.0], true, true).is_none()); + } +} + +#[test] +fn releasing_alt_mid_corner_drag_puts_the_neighbours_back() { + // ⌥ released during the drag: the corner then moves alone, from the quad at the press. + let mut app = app(); + let q = [[100.0, 100.0], [500.0, 100.0], [500.0, 400.0], [100.0, 400.0]]; + app.ui.perspective_crop = Some(q); + assert!(pointer(&mut app, ToolEvent::Down { x: 500.0, y: 400.0, pressure: 1.0 }, ALT)); + assert!(pointer(&mut app, ToolEvent::Move { x: 740.0, y: 430.0, pressure: 1.0 }, ALT)); + assert_eq!(app.ui.perspective_crop, rect(100.0, 100.0, 740.0, 430.0)); + assert!(pointer(&mut app, ToolEvent::Move { x: 700.0, y: 450.0, pressure: 1.0 }, Modifiers::NONE)); + assert_eq!(app.ui.perspective_crop, Some([q[0], q[1], [700.0, 450.0], q[3]]), "the preview during the drag"); + assert!(pointer(&mut app, ToolEvent::Up { x: 700.0, y: 450.0 }, Modifiers::NONE)); + assert_eq!(app.ui.perspective_crop, Some([q[0], q[1], [700.0, 450.0], q[3]])); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_shield_tests.rs b/crates/ui-egui/src/tools/perspective_crop_shield_tests.rs new file mode 100644 index 0000000000..c210a46095 --- /dev/null +++ b/crates/ui-egui/src/tools/perspective_crop_shield_tests.rs @@ -0,0 +1,97 @@ +//! #11972: with a pending Perspective Crop quad the image outside it is dimmed (red 255, 0, 0 shows +//! as about 225, 16, 16), inside it is unchanged, the shield follows the quad while it is dragged, +//! and nothing is drawn without a quad. + +use egui::{Pos2, Rect, vec2}; +use serde_json::json; + +use super::*; + +const CANVAS: [[f64; 2]; 4] = [[0.0, 0.0], [200.0, 0.0], [200.0, 150.0], [0.0, 150.0]]; + +fn area(poly: &[[f64; 2]]) -> f64 { + (0..poly.len()).map(|i| poly[i][0] * poly[(i + 1) % poly.len()][1] - poly[(i + 1) % poly.len()][0] * poly[i][1]).sum::().abs() / 2.0 +} + +/// A point strictly inside a convex polygon. +fn contains(poly: &[[f64; 2]], p: [f64; 2]) -> bool { + let s: Vec = (0..poly.len()) + .map(|i| { + let (a, b) = (poly[i], poly[(i + 1) % poly.len()]); + (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) + }) + .collect(); + s.iter().all(|v| *v > 1e-9) || s.iter().all(|v| *v < -1e-9) +} + +#[test] +fn the_shield_colour_dims_red_as_measured() { + // Straight alpha over an opaque pixel: v · (1 − a) + grey · a. + let a = f32::from(SHIELD.a()) / 255.0; + let grey = f32::from(SHIELD.r()) / a; + let over = |v: f32| v * (1.0 - a) + grey * a; + let [r, g, b] = [over(255.0), over(0.0), over(0.0)]; + assert!((r - 225.0).abs() <= 4.0 && (g - 16.0).abs() <= 4.0 && (b - 16.0).abs() <= 4.0, "{r} {g} {b}"); +} + +#[test] +fn the_pieces_cover_the_canvas_outside_the_quad_and_never_inside() { + // A skewed quad inside the canvas, in either winding. + for q in [[[30.0, 20.0], [170.0, 30.0], [160.0, 120.0], [40.0, 110.0]], [[40.0, 110.0], [160.0, 120.0], [170.0, 30.0], [30.0, 20.0]]] { + let pieces = shield_pieces(CANVAS, q); + let covered: f64 = pieces.iter().map(|p| area(p)).sum(); + assert!((covered - (area(&CANVAS) - area(&q))).abs() < 1e-6, "{covered}"); + for p in [[100.0, 70.0], [50.0, 40.0], [150.0, 100.0]] { + assert!(!pieces.iter().any(|piece| contains(piece, p)), "{p:?} inside the quad is not dimmed"); + } + for p in [[5.0, 5.0], [195.0, 145.0], [100.0, 5.0], [5.0, 75.0]] { + assert_eq!(pieces.iter().filter(|piece| contains(piece, p)).count(), 1, "{p:?} outside is dimmed once"); + } + } +} + +#[test] +fn a_quad_past_the_canvas_dims_only_the_canvas() { + let q = [[100.0, 50.0], [260.0, 50.0], [260.0, 200.0], [100.0, 170.0]]; + let pieces = shield_pieces(CANVAS, q); + let inside_canvas = 100.0 * 100.0; // the quad's part on the canvas: x 100–200, y 50–150 + let covered: f64 = pieces.iter().map(|p| area(p)).sum(); + assert!((covered - (area(&CANVAS) - inside_canvas)).abs() < 1e-6, "{covered}"); + assert!(pieces.iter().all(|p| p.iter().all(|v| (0.0..=200.0).contains(&v[0]) && (0.0..=150.0).contains(&v[1]))), "nothing past the canvas"); +} + +#[test] +fn a_degenerate_quad_has_no_shield() { + assert!(shield_pieces(CANVAS, [[10.0, 10.0], [10.0, 10.0], [10.0, 10.0], [10.0, 10.0]]).is_empty()); + assert!(shield_pieces(CANVAS, [[f64::NAN, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]).is_empty()); +} + +/// The shield polygons `draw_overlay` paints. +fn painted(app: &PhotocraftApp) -> usize { + let ctx = egui::Context::default(); + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 150.0)), zoom: 1.0, center: [100.0, 75.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut o = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf)); + o.textures_delta.clear(); + o.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Path(p) if p.fill == SHIELD)).count() +} + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.ui.tool = Tool::PerspectiveCrop; + app +} + +#[test] +fn the_shield_shows_with_a_quad_follows_a_drag_and_goes_away() { + let mut app = app(); + assert_eq!(painted(&app), 0, "no quad: no shield"); + // While the first box is dragged. + app.pcrop.drag = Some(Drag::New { start: [20.0, 20.0], cur: [180.0, 130.0], square: false, centred: false }); + assert!(painted(&app) > 0, "the shield follows the box being dragged"); + app.pcrop.drag = None; + app.ui.perspective_crop = Some([[20.0, 20.0], [180.0, 20.0], [180.0, 130.0], [20.0, 130.0]]); + assert_eq!(painted(&app), 4, "four pieces around a pending quad"); + cancel(&mut app); + assert_eq!(painted(&app), 0, "gone after cancel"); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index ed60c90d41..1b1a4b3a51 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -8,8 +8,8 @@ //! wound like its box, which can't be committed; //! - ↵ (or ✓) commits: `image.perspectiveCrop` maps the quad onto an upright rectangle, the whole //! document in one undo step. Its size comes from the options bar's W x H (and the resolution), -//! which are the Crop tool's fields (`crop_size`), or with them empty from the quad's mean side -//! lengths. Esc (or ⊘) cancels. +//! which are the Crop tool's fields (`crop_size`), or with them empty from the rectangle the +//! quad shows in perspective. Esc (or ⊘) cancels. //! //! A pending quad belongs to the document it was drawn on, like the Crop tool's frame. @@ -27,10 +27,11 @@ const CLICK_PX: f64 = 3.0; #[derive(Clone, Copy, Debug)] pub enum Drag { - /// Drawing a box from `start`. - New { start: [f64; 2], cur: [f64; 2] }, - /// Moving one corner; `offset` is the press's distance from it. - Corner { index: usize, offset: [f64; 2] }, + /// Drawing a box from `start`; ⇧ makes it a square, ⌥ centres it on `start` (#11802). + New { start: [f64; 2], cur: [f64; 2], square: bool, centred: bool }, + /// Moving one corner; `offset` is the press's distance from it, `press` where the press was + /// and `quad` the quad then (⇧ keeps one axis, ⌥ keeps a rectangle one, #11802). + Corner { index: usize, offset: [f64; 2], press: [f64; 2], quad: [[f64; 2]; 4] }, /// Moving the whole quad. Move { start: [f64; 2], quad: [[f64; 2]; 4] }, } @@ -59,7 +60,7 @@ pub fn pending(app: &PhotocraftApp) -> bool { pub fn dragging(app: &PhotocraftApp) -> bool { app.ui.tool == Tool::PerspectiveCrop && match app.pcrop.drag { - Some(Drag::New { start, cur }) => !is_click(app, start, cur), + Some(Drag::New { start, cur, .. }) => !is_click(app, start, cur), Some(_) => true, None => false, } @@ -105,8 +106,33 @@ fn inside(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool { }) } -/// Pointer events (document px) with the tool. True when consumed. -pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent) -> bool { +/// The box a new drag from `start` to `cur` draws (document px, x0, y0, x1, y1): ⇧ makes it a +/// square of the shorter drag side in the drag's direction, ⌥ centres it on `start` at twice the +/// drag, both together a centred square (#11802). `None` without area. +pub(crate) fn new_box(start: [f64; 2], cur: [f64; 2], square: bool, centred: bool) -> Option<[[f64; 2]; 4]> { + let (mut dx, mut dy) = (cur[0] - start[0], cur[1] - start[1]); + if square { + let side = dx.abs().min(dy.abs()); + (dx, dy) = (side.copysign(dx), side.copysign(dy)); + } + let (a, b) = if centred { ([start[0] - dx, start[1] - dy], [start[0] + dx, start[1] + dy]) } else { (start, [start[0] + dx, start[1] + dy]) }; + let (x0, y0, x1, y1) = (a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])); + // A straight drag has no area: no box (it could neither be committed nor replaced by a new + // drag). + (x1 > x0 && y1 > y0).then_some([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]) +} + +/// Whether every side of `q` is either horizontal or vertical: a rectangle on the image's axes, +/// which ⌥ keeps one while a corner is dragged. +fn axis_rect(q: &[[f64; 2]; 4]) -> bool { + (0..4).all(|i| { + let (a, b) = (q[i], q[(i + 1) % 4]); + (a[0] == b[0]) != (a[1] == b[1]) + }) +} + +/// Pointer events (document px) with the tool and the held modifiers. True when consumed. +pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { if app.ui.tool != Tool::PerspectiveCrop { app.pcrop.drag = None; return false; @@ -127,18 +153,18 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent) -> bool { .filter(|&i| (q[i][0] - p[0]).hypot(q[i][1] - p[1]) <= tol) .min_by(|&i, &j| (q[i][0] - p[0]).hypot(q[i][1] - p[1]).total_cmp(&(q[j][0] - p[0]).hypot(q[j][1] - p[1]))); match near { - Some(index) => Some(Drag::Corner { index, offset: [p[0] - q[index][0], p[1] - q[index][1]] }), + Some(index) => Some(Drag::Corner { index, offset: [p[0] - q[index][0], p[1] - q[index][1]], press: p, quad: q }), None if inside(&q, p) => Some(Drag::Move { start: p, quad: q }), None => None, } } - None => Some(Drag::New { start: p, cur: p }), + None => Some(Drag::New { start: p, cur: p, square: mods.shift, centred: mods.alt }), }; } - ToolEvent::Move { .. } => drag_to(app, p), + ToolEvent::Move { .. } => drag_to(app, p, mods), ToolEvent::Up { .. } => { - drag_to(app, p); - if let Some(Drag::New { start, cur }) = app.pcrop.drag { + drag_to(app, p, mods); + if let Some(Drag::New { start, cur, square, centred }) = app.pcrop.drag { if is_click(app, start, cur) { app.pcrop.clicks.push(start); if let [a, b, c, d] = app.pcrop.clicks[..] { @@ -147,10 +173,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent) -> bool { } } else { app.pcrop.clicks.clear(); - let (x0, y0, x1, y1) = (start[0].min(cur[0]), start[1].min(cur[1]), start[0].max(cur[0]), start[1].max(cur[1])); - // A straight drag has no area: no box (it could neither be committed nor - // replaced by a new drag). - app.ui.perspective_crop = (x1 > x0 && y1 > y0).then_some([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]); + app.ui.perspective_crop = new_box(start, cur, square, centred); } } app.pcrop.drag = None; @@ -159,12 +182,38 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent) -> bool { true } -fn drag_to(app: &mut PhotocraftApp, p: [f64; 2]) { +fn drag_to(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { match app.pcrop.drag { - Some(Drag::New { start, .. }) => app.pcrop.drag = Some(Drag::New { start, cur: p }), - Some(Drag::Corner { index, offset }) => { - if let Some(c) = app.ui.perspective_crop.as_mut().and_then(|q| q.get_mut(index)) { - *c = [p[0] - offset[0], p[1] - offset[1]]; + // The modifiers held now shape the box, as the Frame tool's (not measured mid-drag). + Some(Drag::New { start, .. }) => app.pcrop.drag = Some(Drag::New { start, cur: p, square: mods.shift, centred: mods.alt }), + Some(Drag::Corner { index, offset, press, quad }) => { + let Some(from) = quad.get(index).copied() else { return }; + let mut c = [p[0] - offset[0], p[1] - offset[1]]; + // ⇧: along the axis the drag mostly follows since the press; the other stays. + if mods.shift { + if (p[0] - press[0]).abs() >= (p[1] - press[1]).abs() { + c[1] = from[1]; + } else { + c[0] = from[0]; + } + } + let Some(q) = app.ui.perspective_crop.as_mut() else { return }; + // Each move starts from the quad at the press, so ⌥ released mid-drag puts the + // neighbours back. + *q = quad; + // ⌥ on a rectangle: the neighbours follow, one coordinate each, the opposite corner + // stays. On any other quad (not measured) the corner moves alone. + if mods.alt && axis_rect(&quad) { + for j in [(index + 1) % 4, (index + 3) % 4] { + if quad[j][0] == from[0] { + q[j][0] = c[0]; + } else { + q[j][1] = c[1]; + } + } + } + if let Some(corner) = q.get_mut(index) { + *corner = c; } } Some(Drag::Move { start, quad }) => { @@ -233,6 +282,51 @@ fn grid_steps(side: f32) -> usize { ((side / 48.0).round() as usize).clamp(2, 12) } +/// The shield over the image outside a pending quad (#11972): grey 89 at 18 % opacity, which shows +/// red 255, 0, 0 as 225, 16, 16, as measured in the reference application. +pub(crate) const SHIELD: Color32 = Color32::from_rgba_premultiplied(16, 16, 16, 46); + +/// The canvas `canvas` (a convex polygon, document px) minus the convex quad `q`, as up to four +/// disjoint convex pieces: each is what is left of the canvas outside one quad edge and inside the +/// edges before it. Empty for a degenerate quad. +pub(crate) fn shield_pieces(canvas: [[f64; 2]; 4], q: [[f64; 2]; 4]) -> Vec> { + let area: f64 = (0..4).map(|i| q[i][0] * q[(i + 1) % 4][1] - q[(i + 1) % 4][0] * q[i][1]).sum(); + if !area.is_finite() || area.abs() < 1e-9 { + return Vec::new(); + } + let side = area.signum(); + let mut rest = canvas.to_vec(); + let mut out = Vec::new(); + for i in 0..4 { + let (a, b) = (q[i], q[(i + 1) % 4]); + let outside = clip_half_plane(&rest, a, b, -side); + if outside.len() >= 3 { + out.push(outside); + } + rest = clip_half_plane(&rest, a, b, side); + } + out +} + +/// One Sutherland–Hodgman step: the part of the convex polygon `poly` on the `side` (the sign of +/// the cross product) of the line from `a` to `b`. +fn clip_half_plane(poly: &[[f64; 2]], a: [f64; 2], b: [f64; 2], side: f64) -> Vec<[f64; 2]> { + let d = |p: [f64; 2]| side * ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])); + let mut out = Vec::with_capacity(poly.len() + 1); + for (i, &p) in poly.iter().enumerate() { + let n = poly[(i + 1) % poly.len()]; + let (dp, dn) = (d(p), d(n)); + if dp >= 0.0 { + out.push(p); + } + if (dp >= 0.0) != (dn >= 0.0) && (dp - dn).abs() > f64::EPSILON { + let t = dp / (dp - dn); + out.push([p[0] + (n[0] - p[0]) * t, p[1] + (n[1] - p[1]) * t]); + } + } + out +} + /// The quad, its perspective grid and corner handles; corners clicked so far; the box being drawn. pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) { if app.ui.tool != Tool::PerspectiveCrop { @@ -241,15 +335,19 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform let scr = |p: [f64; 2]| xf.to_screen(p[0] as f32, p[1] as f32); let accent = crate::theme::Tokens::get(painter.ctx()).accent; let quad = match app.pcrop.drag { - Some(Drag::New { start, cur }) => { - let (x0, y0, x1, y1) = (start[0].min(cur[0]), start[1].min(cur[1]), start[0].max(cur[0]), start[1].max(cur[1])); - (x1 > x0 && y1 > y0).then_some([[x0, y0], [x1, y0], [x1, y1], [x0, y1]]) - } + Some(Drag::New { start, cur, square, centred }) => new_box(start, cur, square, centred), _ => app.ui.perspective_crop, }; if let Some(q) = quad.filter(|q| q.iter().flatten().all(|v| v.is_finite())) { let ok = convex_quad(&q); let color = if ok { accent } else { Color32::from_rgb(0xe5, 0x3e, 0x3e) }; + // The image outside the quad is dimmed (#11972), following the quad while it is dragged. + if ok && let Some(size) = app.session.active().map(|d| d.doc.size) { + let (w, h) = (f64::from(size.width), f64::from(size.height)); + for piece in shield_pieces([[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]], q) { + painter.add(egui::Shape::convex_polygon(piece.iter().map(|c| scr(*c)).collect(), SHIELD, Stroke::NONE)); + } + } let pts: Vec = q.iter().map(|c| scr(*c)).collect(); if ok && app.ui.tool_options.perspective_crop_grid @@ -305,6 +403,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } crate::widgets::vline(ui, 22.0); crate::widgets::checkbox(ui, &mut app.ui.tool_options.perspective_crop_grid, tl!("Show Grid")); + // Commit and Cancel show only during a session: a quad, clicked corners, or a drag (#11978). + if !pending(app) { + return; + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let commit_tip = crate::i18n::fmt(tl!("Commit current crop operation ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]); if crate::icons::button(ui, "check", 26.0, false, &commit_tip).clicked() { @@ -316,6 +418,18 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); } +#[cfg(test)] +#[path = "perspective_crop_bar_buttons_tests.rs"] +mod perspective_crop_bar_buttons_tests; + +#[cfg(test)] +#[path = "perspective_crop_modifiers_tests.rs"] +mod perspective_crop_modifiers_tests; + +#[cfg(test)] +#[path = "perspective_crop_shield_tests.rs"] +mod perspective_crop_shield_tests; + #[cfg(test)] mod tests { use super::*; @@ -330,7 +444,7 @@ mod tests { s.add_document(doc, None); let mut app = PhotocraftApp::new(s, crate::Services::default()); app.ui.tool = Tool::PerspectiveCrop; - let ev = |app: &mut PhotocraftApp, e| assert!(pointer(app, e)); + let ev = |app: &mut PhotocraftApp, e| assert!(pointer(app, e, egui::Modifiers::NONE)); for (x1, y1) in [(10.0, 60.0), (90.0, 10.0)] { ev(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }); ev(&mut app, ToolEvent::Move { x: x1, y: y1, pressure: 1.0 }); @@ -549,7 +663,7 @@ mod tests { s.add_document(doc, None); let mut app = PhotocraftApp::new(s, crate::Services::default()); app.ui.tool = Tool::PerspectiveCrop; - let ev = |app: &mut PhotocraftApp, e| assert!(pointer(app, e)); + let ev = |app: &mut PhotocraftApp, e| assert!(pointer(app, e, egui::Modifiers::NONE)); ev(&mut app, ToolEvent::Down { x: 20.0, y: 10.0, pressure: 1.0 }); ev(&mut app, ToolEvent::Move { x: 120.0, y: 90.0, pressure: 1.0 }); ev(&mut app, ToolEvent::Up { x: 120.0, y: 90.0 }); @@ -560,11 +674,26 @@ mod tests { commit(&mut app); assert!(app.ui.perspective_crop.is_none()); let size = app.session.active().unwrap().doc.size; - assert_eq!((size.width, size.height), (110, 86), "the quad's mean side lengths"); + assert_eq!((size.width, size.height), (120, 92), "the quad's longest edges: no camera at the centre can see this rectangle"); assert_eq!(ordered([[10.0, 90.0], [100.0, 5.0], [0.0, 0.0], [90.0, 100.0]]), [[0.0, 0.0], [100.0, 5.0], [90.0, 100.0], [10.0, 90.0]]); } + /// ↵ with W and H empty gives the command's perspective size, not the quad's edges (#11798). + #[test] + fn commit_with_w_and_h_empty_takes_the_perspective_size() { + let doc = Document::with_background("p", Size::new(800, 500), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut s = photocraft_engine::Session::new(); + s.add_document(doc, None); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.ui.tool = Tool::PerspectiveCrop; + app.ui.perspective_crop = Some([[100.0, 50.0], [700.0, 80.0], [760.0, 450.0], [40.0, 420.0]]); + commit(&mut app); + assert!(app.ui.perspective_crop.is_none()); + let size = app.session.active().unwrap().doc.size; + assert!(size.width.abs_diff(731) <= 1 && size.height.abs_diff(588) <= 1, "{} x {}", size.width, size.height); + } + /// Clicking ⇄ in the rendered options bar swaps W and H, although Perspective Crop never sets /// the Crop tool's W x H x Resolution mode (#7059). #[test] @@ -606,7 +735,7 @@ mod tests { s.set_active(0); let mut app = PhotocraftApp::new(s, crate::Services::default()); app.ui.tool = Tool::PerspectiveCrop; - let ev = |app: &mut PhotocraftApp, e| assert!(pointer(app, e)); + let ev = |app: &mut PhotocraftApp, e| assert!(pointer(app, e, egui::Modifiers::NONE)); ev(&mut app, ToolEvent::Down { x: 20.0, y: 10.0, pressure: 1.0 }); ev(&mut app, ToolEvent::Move { x: 120.0, y: 90.0, pressure: 1.0 }); ev(&mut app, ToolEvent::Up { x: 120.0, y: 90.0 }); diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 540cf5879a..792f74c4bb 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -29,9 +29,9 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { let o = &app.ui.tool_options; // The options bar's Mode is the tool's own brush's. let mode = crate::blend_keys::brush_tool_mode(app.ui.tool, app.session.tools.brush.mode); - let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample, "mode": mode.label()}); + // View › Pattern Preview: both tools carry a stroke on across the canvas edges (#8883). + let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview}); if app.ui.tool == Tool::CloneStamp { - p["wrap"] = json!(app.ui.view.pattern_preview); p["opacity"] = json!(app.session.tools.brush.opacity * 100.0); p["flow"] = json!(app.session.tools.brush.flow * 100.0); } @@ -337,6 +337,17 @@ pub fn cancel_stale(app: &mut PhotocraftApp) { } } +/// Where a Patch drag ends: with ⇧ pressed after the press (⇧ at the press adds to the selection +/// instead, so this never sees it) the end is held to the dominant axis from the start, 0 or 90 +/// degrees only (#12129). Other tools, and a drag without ⇧, end at `end`. +pub fn patch_end(d: &crate::canvas::Drag, end: [f64; 2]) -> [f64; 2] { + if d.tool != Tool::Patch || !d.live.shift { + return end; + } + let (dx, dy) = (end[0] - d.start[0], end[1] - d.start[1]); + if dx.abs() >= dy.abs() { [end[0], d.start[1]] } else { [d.start[0], end[1]] } +} + /// Whole-pixel offset for a drag from `start` to `end`, limited so the dragged outline stays on the /// canvas (the engine rejects a patch or move that leaves it). pub fn patch_offset(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) -> [i32; 2] { @@ -414,6 +425,85 @@ pub fn finish_content_aware_move(app: &mut PhotocraftApp, start: [f64; 2], end: } } +/// The Content-Aware Move tool's "Don't show again" for [`content_aware_move_no_pixels`]. +const CAM_NO_PIXELS_PREF: &str = "contentAwareMove.noPixelsSelected"; + +/// Content-Aware Move Tool with no selection: a drag whose lasso would select no pixel (a click, +/// a straight line) selects nothing and adds no History state, and says so in the alert "No pixels +/// are selected." with "Don't show again" (#12192). Returns whether this drag was such a one. With +/// a selection, or a lasso that selects pixels, it is the tool's lasso as before. +pub fn content_aware_move_no_pixels(app: &mut PhotocraftApp, points: &[[f64; 2]]) -> bool { + let Some(canvas) = app.session.active().filter(|s| s.doc.selection.is_none()).map(|s| s.doc.bounds()) else { return false }; + if lasso_selects_pixels(points, canvas, app.ui.tool_options.anti_alias) { + return false; + } + crate::dialogs::dont_show_again::alert(app, tl!("No pixels are selected."), CAM_NO_PIXELS_PREF); + true +} + +/// Whether `select.lasso` through `points` would select any pixel of `canvas`: the same +/// rasterization (its coverage over the canvas's coordinates), kept where it rounds to a nonzero +/// 8-bit value as the selection stores it. Only the lasso's bounds are rasterized, a strip of rows +/// at a time, stopping at the first selected pixel. The strips start at 64 rows, so a lasso that +/// selects is answered after the first, and double up to about 4 MP (16 MB), so a lasso that +/// selects nothing (a long line) is rasterized and scanned in parallel: a corner-to-corner line +/// on 7360 x 4912 takes 25-32 ms, about what the `select.lasso` it replaces took (23-27 ms). +fn lasso_selects_pixels(points: &[[f64; 2]], canvas: photocraft_geom::Rect, anti_alias: bool) -> bool { + const FIRST_STRIP: u32 = 64; + const MAX_STRIP_PIXELS: u32 = 1 << 22; + // `coverage8` of the selection combine: the 8-bit value a pixel's coverage is stored as. It + // only grows with the coverage, so a pixel is kept from the least coverage it keeps (found + // once over the f32 bits in [0, 1]), and the scan is a single compare per pixel. + let stored = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let (mut below, mut kept) = (0u32, 1.0f32.to_bits()); + while kept - below > 1 { + let mid = below + (kept - below) / 2; + if stored(f32::from_bits(mid)) > 0 { kept = mid } else { below = mid } + } + let least = f32::from_bits(kept); + // As `select.lasso` reads the points. + let pts: Vec<(f32, f32)> = points.iter().map(|p| (p[0] as f32, p[1] as f32)).collect(); + if pts.len() < 3 { + return false; + } + let (mut lo, mut hi) = ((f32::INFINITY, f32::INFINITY), (f32::NEG_INFINITY, f32::NEG_INFINITY)); + for &(x, y) in pts.iter().filter(|(x, y)| x.is_finite() && y.is_finite()) { + lo = (lo.0.min(x), lo.1.min(y)); + hi = (hi.0.max(x), hi.1.max(y)); + } + if lo.0 > hi.0 || lo.1 > hi.1 { + return false; + } + // Saturating float-to-int casts; the canvas clips them. + let bounds = + photocraft_geom::Rect::new(lo.0.floor() as i32, lo.1.floor() as i32, (hi.0.ceil() as i32).saturating_add(1), (hi.1.ceil() as i32).saturating_add(1)); + let window = bounds.intersect(&canvas); + let max_rows = (MAX_STRIP_PIXELS / window.width().max(1)).max(FIRST_STRIP); + let (mut y, mut rows) = (window.y0, FIRST_STRIP); + while y < window.y1 { + let strip = photocraft_geom::Rect::new(window.x0, y, window.x1, y.saturating_add_unsigned(rows).min(window.y1)); + if any_at_least(&photocraft_algo::selection::polygon_window(&pts, canvas, strip, anti_alias), least) { + return true; + } + y = strip.y1; + rows = rows.saturating_mul(2).min(max_rows); + } + false +} + +/// Whether any of `mask` is at least `least`: in parallel blocks, each one a branch-free pass the +/// compiler vectorizes. +fn any_at_least(mask: &[f32], least: f32) -> bool { + let block = |b: &[f32]| b.iter().fold(false, |found, v| found | (*v >= least)); + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + mask.par_chunks(1 << 16).any(block) + } + #[cfg(target_arch = "wasm32")] + mask.chunks(1 << 16).any(block) +} + /// `paint.contentAwareMove`'s params for a drag by `offset`, from the options bar. pub fn content_aware_move_params(app: &PhotocraftApp, offset: [i64; 2]) -> Value { let o = &app.ui.tool_options; @@ -525,6 +615,128 @@ fn pct(ui: &mut egui::Ui, label: &str, v: &mut f32) { crate::widgets::value_field(ui, v, 1.0..=100.0, "%", 58.0); } +const STRUCTURE_RANGE_ALERT: &str = "An integer between 1 and 7 is required. Closest value inserted."; +const COLOR_RANGE_ALERT: &str = "An integer between 0 and 10 is required. Closest value inserted."; +const STRUCTURE_TIP: &str = "Adjust how strictly the source structure is preserved"; +const COLOR_TIP: &str = "Adjust how much the source color can be modified"; + +/// Structure or Color on the Content-Aware Move bar (#12193): a whole-number field and a slider +/// popup. A typed value outside `lo..=hi` becomes the closest value; returns true once the field +/// is left, so the caller opens the alert. A scrub stops at the end without an alert. +fn cam_integer_popup(ui: &mut egui::Ui, id: &str, name: &str, value: &mut f32, lo: f32, hi: f32, tip: &str) -> bool { + *value = if value.is_finite() { value.round().clamp(lo, hi) } else { lo }; + let draft_id = ui.make_persistent_id(egui::IdSalt::new(id)).with("typed"); + let draft = ui.ctx().data(|d| d.get_temp::<(f32, f32)>(draft_id)); + let mut typed = draft.filter(|(_, stored)| *stored == *value).map_or(*value, |(typed, _)| typed); + // Wide range so a typed 99 reaches here unclamped. The caption just before this names the field. + let r = crate::widgets::value_field(ui, &mut typed, -1.0e9..=1.0e9, "", 40.0).on_hover_text(tl!(tip)); + let out_id = r.id.with("out-of-range"); + if r.gained_focus() { + ui.ctx().data_mut(|d| d.remove_temp::(out_id)); + } + if r.changed() && typed.is_finite() { + *value = typed.round().clamp(lo, hi); + let typing = (r.has_focus() || r.lost_focus()) && ui.ctx().dragged_id().is_none(); + let out = typing && !(lo..=hi).contains(&typed); + ui.ctx().data_mut(|d| d.insert_temp(out_id, out)); + if typing && r.has_focus() { + ui.ctx().data_mut(|d| d.insert_temp(draft_id, (typed, *value))); + } else { + ui.ctx().data_mut(|d| d.remove_temp::<(f32, f32)>(draft_id)); + } + } + if !r.has_focus() { + ui.ctx().data_mut(|d| d.remove_temp::<(f32, f32)>(draft_id)); + } + cam_amount_slider(ui, name, value, lo, hi, tip); + r.lost_focus() && ui.ctx().data_mut(|d| d.remove_temp::(out_id)).unwrap_or(false) +} + +/// The ▾ beside a Content-Aware Move amount: its pop-up slider snaps to whole numbers in `lo..=hi`. +fn cam_amount_slider(ui: &mut egui::Ui, name: &str, value: &mut f32, lo: f32, hi: f32, tip: &str) { + let (rect, resp) = ui.allocate_exact_size(vec2(14.0, 22.0), egui::Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), name)); + let resp = resp.on_hover_text(tl!(tip)); + let popup = egui::Popup::from_toggle_button_response(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + let open = popup.is_open(); + if resp.hovered() || open { + let t = Tokens::get(ui.ctx()); + ui.painter().rect_filled(rect, t.radius_sm, t.field_border.gamma_multiply(0.6)); + } + crate::widgets::chevron_icon(ui, rect, ui.style().interact(&resp), open); + let parent_layer = resp.layer_id; + popup.show(|ui| { + crate::press_menu::above_parent_ui(parent_layer, ui); + ui.set_min_width(160.0); + let mut v = *value; + let s = crate::widgets::slider(ui, &mut v, lo..=hi, None); + if v.is_finite() { + let snapped = v.round().clamp(lo, hi); + if snapped != *value { + *value = snapped; + } + } + s.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(*value), name)); + }); +} + +fn open_cam_range_alert(app: &mut PhotocraftApp, message: &str) { + let message = tl!(message).to_owned(); + let shown = + app.ui.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(message.as_str())); + if !shown { + app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } +} + +/// Content-Aware Move's options (#12193). While the Transform On Drop box is up, the controls are +/// greyed and Cancel then Commit sit at the right end. +fn content_aware_move_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let live = crate::cam_transform::active(app); + ui.add_enabled_ui(!live, |ui| { + crate::panels::selection_mode_buttons(&mut app.ui.selection_mode, ui); + crate::widgets::vline(ui, 22.0); + opt(ui, tl!("Mode:")); + let modes = [("move".to_string(), tl!("Move")), ("extend".to_string(), tl!("Extend"))]; + crate::widgets::dropdown(ui, "cam-mode", tl!("Mode"), &mut app.ui.tool_options.cam_mode, &modes, 90.0); + if let Some(mode) = ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new("cam-mode"))) { + mode.on_hover_text(tl!("Choose a remix mode")); + } + opt(ui, tl!("Structure:")); + if cam_integer_popup(ui, "cam-structure", "Structure", &mut app.ui.tool_options.cam_structure, 1.0, 7.0, STRUCTURE_TIP) { + open_cam_range_alert(app, STRUCTURE_RANGE_ALERT); + } + opt(ui, tl!("Color:")); + if cam_integer_popup(ui, "cam-color", "Color", &mut app.ui.tool_options.cam_color, 0.0, 10.0, COLOR_TIP) { + open_cam_range_alert(app, COLOR_RANGE_ALERT); + } + crate::widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.content_aware_move, tl!("Sample All Layers")) + .on_hover_text(tl!("Enable to remix all layers")); + crate::widgets::checkbox(ui, &mut app.ui.tool_options.cam_transform_on_drop, tl!("Transform On Drop")) + .on_hover_text(tl!("Allows rotation and scaling of selection")); + }); + crate::widgets::vline(ui, 22.0); + if live { + // right_to_left places the first widget at the right, so Commit is the rightmost and + // Cancel sits just to its left. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let tip = crate::i18n::fmt(tl!("Commit transform ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]); + let commit = crate::icons::button(ui, "check", 26.0, false, &tip); + commit.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Commit transform")); + if commit.clicked() { + crate::cam_transform::commit(app); + } + let cancel = crate::icons::button(ui, "ban", 26.0, false, tl!("Cancel transform (Esc)")); + cancel.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Cancel transform")); + if cancel.clicked() { + crate::cam_transform::cancel(app); + } + }); + } else { + opt(ui, tl!("Lasso around an area, then drag the selection")); + } +} + /// Options bar for the retouching and smart-selection tools. Returns false for other tools. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { if !tool.is_brushlike() && !matches!(tool, Tool::QuickSelection | Tool::ObjectSelection | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye) @@ -532,6 +744,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo { return false; } + if tool == Tool::ContentAwareMove { + content_aware_move_bar(app, ui); + return true; + } let composite = crate::canvas::paint_target(app).as_str() == Some("pixels"); let o = &mut app.ui.tool_options; match tool { @@ -592,37 +808,6 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::vline(ui, 22.0); opt(ui, tl!("Lasso around an area, then drag the selection")); } - Tool::ContentAwareMove => { - // The lasso's selection mode leads, as on the Patch tool's bar (#11024). - crate::panels::selection_mode_buttons(&mut app.ui.selection_mode, ui); - crate::widgets::vline(ui, 22.0); - opt(ui, tl!("Mode:")); - let modes = [("move".to_string(), tl!("Move")), ("extend".to_string(), tl!("Extend"))]; - crate::widgets::dropdown(ui, "cam-mode", tl!("Mode"), &mut o.cam_mode, &modes, 90.0); - opt(ui, tl!("Structure:")); - crate::widgets::value_field(ui, &mut o.cam_structure, 1.0..=7.0, "", 40.0); - opt(ui, tl!("Color:")); - crate::widgets::value_field(ui, &mut o.cam_color, 0.0..=10.0, "", 40.0); - crate::widgets::checkbox(ui, &mut o.sample_all.content_aware_move, tl!("Sample All Layers")); - crate::widgets::checkbox(ui, &mut o.cam_transform_on_drop, tl!("Transform On Drop")); - crate::widgets::vline(ui, 22.0); - if crate::cam_transform::active(app) { - // The box on the dropped patch: ✓ computes the move, ⊘ drops it (as ↩ / Esc). - let tip = crate::i18n::fmt(tl!("Commit transform ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]); - let commit = crate::icons::button(ui, "check", 26.0, false, &tip); - commit.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Commit transform")); - if commit.clicked() { - crate::cam_transform::commit(app); - } - let cancel = crate::icons::button(ui, "ban", 26.0, false, tl!("Cancel transform (Esc)")); - cancel.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Cancel transform")); - if cancel.clicked() { - crate::cam_transform::cancel(app); - } - } else { - opt(ui, tl!("Lasso around an area, then drag the selection")); - } - } Tool::PatternStamp => { pattern_stamp_options(app, ui); } @@ -800,3 +985,7 @@ fn pattern_stamp_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "../cam_options_bar_tests.rs"] +mod cam_options_bar_tests; diff --git a/crates/ui-egui/src/tools/retouch_ui/tests.rs b/crates/ui-egui/src/tools/retouch_ui/tests.rs index 375f8a410a..5d1923cb4e 100644 --- a/crates/ui-egui/src/tools/retouch_ui/tests.rs +++ b/crates/ui-egui/src/tools/retouch_ui/tests.rs @@ -28,6 +28,44 @@ fn stripes(app: &mut PhotocraftApp, step: usize, target: &str) { } } +#[test] +fn only_clone_stamp_and_healing_brush_wrap_in_pattern_preview() { + // View › Pattern Preview (#8883): a Clone Stamp or Healing Brush stroke across the right edge + // asks its command to go on at the opposite one, and only then. The reference application's + // other retouching tools stop at the edge. + let tools = [ + (Tool::CloneStamp, "paint.cloneStamp", true), + (Tool::Healing, "paint.healingBrush", true), + (Tool::Blur, "paint.blur", false), + (Tool::Sharpen, "paint.sharpen", false), + (Tool::Smudge, "paint.smudge", false), + (Tool::Dodge, "paint.dodge", false), + (Tool::Burn, "paint.burn", false), + (Tool::Sponge, "paint.sponge", false), + (Tool::ColorReplacement, "paint.colorReplacement", false), + (Tool::PatternStamp, "paint.patternStamp", false), + (Tool::HistoryBrush, "paint.historyBrush", false), + (Tool::SpotHealing, "paint.spotHealing", false), + (Tool::BackgroundEraser, "paint.backgroundEraser", false), + ]; + for (tool, cmd, wraps) in tools { + for pattern_preview in [false, true] { + let mut app = app(); + stripes(&mut app, 8, "pixels"); + app.ui.view.pattern_preview = pattern_preview; + app.ui.clone_source = Some([20.0, 30.0]); + app.ui.tool = tool; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 86.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 112.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 112.0, y: 30.0 }, m); + assert!(!app.ui.status_error, "{tool:?}: {}", app.ui.status); + let (_, p) = app.session.journal.iter().rev().find(|(id, _)| id == cmd).cloned().unwrap_or_else(|| panic!("{tool:?}: no {cmd}")); + assert_eq!(p.get("wrap").and_then(Value::as_bool).unwrap_or(false), wraps && pattern_preview, "{tool:?}: {p}"); + } + } +} + #[test] fn clone_stamp_in_pattern_preview_wraps_a_dab_across_the_right_edge() { for pattern_preview in [false, true] { @@ -587,7 +625,8 @@ fn patch_cursor_shows_the_selection_mode_badge() { app.ui.selection_mode = 1; assert_eq!(badge(&app, tool, none), Some(Badge::Add), "{tool:?}: the options-bar mode outside the selection"); app.hover_doc = Some([20.0, 30.0]); - assert_eq!(badge(&app, tool, none), None, "{tool:?}: a press over the selection drags the patch"); + let over = (tool == Tool::Patch).then_some(Badge::Arrow); + assert_eq!(badge(&app, tool, none), over, "{tool:?}: a press over the selection drags the patch (Patch shows an arrow, #12130)"); assert_eq!(badge(&app, tool, shift), Some(Badge::Add), "{tool:?}: ⇧ over the selection adds"); } } @@ -620,6 +659,7 @@ fn content_aware_move_tool_lassoes_then_moves_or_extends() { app.run("paint.pencil", json!({"points": [[20, 30], [24, 30]], "size": 6, "color": "#0000ff"})).unwrap(); let blue = |app: &PhotocraftApp, x: i32| active(app).surface().unwrap().rgba(x, 30)[0] < 0.5; app.ui.tool = Tool::ContentAwareMove; + app.ui.tool_options.cam_transform_on_drop = false; app.ui.tool_options.cam_mode = mode.into(); app.ui.tool_options.cam_structure = 7.0; let m = egui::Modifiers::NONE; diff --git a/crates/ui-egui/src/tools/stroke_trace.rs b/crates/ui-egui/src/tools/stroke_trace.rs index 8bbd1c887a..443c695792 100644 --- a/crates/ui-egui/src/tools/stroke_trace.rs +++ b/crates/ui-egui/src/tools/stroke_trace.rs @@ -83,7 +83,7 @@ impl Summary { } /// Where the trace goes ([`StrokeTrace::from_env`]). -// The web build has no clock, so it never traces. +// The web build never traces: it has no environment, stderr or files to write to. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] #[derive(Clone, Debug, Default, PartialEq)] pub(crate) enum Output { @@ -120,7 +120,7 @@ fn percentiles(mut v: Vec) -> [f64; 2] { } impl StrokeTrace { - /// Reads `PHOTOCRAFT_STROKE_TRACE` (off on the web, where there is no clock). + /// Reads `PHOTOCRAFT_STROKE_TRACE` (off on the web, which has no environment, stderr or files). pub fn from_env() -> Self { #[cfg(not(target_arch = "wasm32"))] if let Some(v) = std::env::var_os("PHOTOCRAFT_STROKE_TRACE") { @@ -202,7 +202,7 @@ impl StrokeTrace { } /// The CSV text for `rows` of stroke `stroke` (with the header when `header`). -// The web build has no clock, so it never traces. +// The web build never traces: it has no environment, stderr or files to write to. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub(crate) fn csv(stroke: usize, rows: &[Row], header: bool) -> String { let mut s = String::new(); diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 148599b50c..a5e2408746 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -15,7 +15,7 @@ //! [`reset_options`] lists the fields of each tool. The selection tools also go back to New //! Selection, and the painting tools (the ones with a brush in the options bar) get their starting //! brush (`paint_mouse::fresh_brush`: the Brush tool's 13 px soft round, the default brush for the -//! others), keeping the colours. Tools without options (Hand, Rotate View, Ruler, Note, …) have +//! others), keeping the colours. Tools without options (Rotate View, Ruler, Note, …) have //! nothing to reset. use serde_json::{Map, Value, json}; @@ -218,7 +218,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Pencil => reset!(pencil_auto_erase, pencil_clear), Tool::Eraser => reset!(eraser_mode), Tool::Remove => reset!(remove_new_layer, remove_after_each_stroke), - Tool::BackgroundEraser => reset!(bg_sampling, bg_limits, bg_tolerance, bg_protect_fg), + Tool::BackgroundEraser => reset!(bg_sampling, bg_limits, bg_tolerance, bg_protect_fg, bg_tolerance_control), Tool::ColorReplacement => reset!(cr_mode, cr_sampling, cr_limits, cr_tolerance, cr_anti_alias), Tool::MagicEraser => reset!(tolerance, anti_alias, contiguous, magic_eraser_opacity), Tool::Gradient => reset!(gradient_style, gradient_reverse, gradient_dither, gradient_classic, gradient_blend_mode, fill_opacity), @@ -227,6 +227,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { reset!(type_font, type_style, type_size, type_aa, type_align, type_direction, type_style_defaults) } Tool::Zoom => reset!(zoom_scrubby), + Tool::Hand => reset!(hand_scroll_all), Tool::SpotHealing => reset!(spot_type), Tool::Healing => reset!(clone_aligned, clone_sample), Tool::Patch => reset!(patch_mode, patch_content_aware, patch_structure, patch_color), @@ -262,12 +263,11 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Star | Tool::CustomShape => { reset!(shape_mode, shape_fill, stroke_width, shape_stroke, shape_fill_gradient, shape_stroke_gradient, corner_radius, polygon_sides, line_weight) } + Tool::MixerBrush => reset!(mixer_combination), Tool::ColorSampler | Tool::Ruler | Tool::Note | Tool::Count - | Tool::MixerBrush - | Tool::Hand | Tool::RotateView | Tool::HistoryBrush | Tool::PathSelection diff --git a/crates/ui-egui/src/tools/transform_tool.rs b/crates/ui-egui/src/tools/transform_tool.rs index a5748ee7e7..e6cb394137 100644 --- a/crates/ui-egui/src/tools/transform_tool.rs +++ b/crates/ui-egui/src/tools/transform_tool.rs @@ -24,6 +24,7 @@ use crate::state::{MadeLayer, Tool, TransformMode, TransformSession}; mod begin; mod commit; +mod cylinder; mod drag_modes; mod draw; mod options_bar; @@ -35,9 +36,12 @@ pub(crate) use begin::begin_content_aware; pub(crate) use begin::moving_layers; #[cfg(test)] pub(crate) use begin::moving_texel; -pub use begin::{WARP_ONE_LAYER, begin, begin_copy, begin_placed, begin_selection, begin_warp, enter_warp, leave_warp, warps_type}; +pub use begin::{WARP_ONE_LAYER, begin, begin_copy, begin_placed, begin_selection, begin_warp, enter_warp, leave_warp, warps_active_layer, warps_type}; pub(crate) use commit::{SAVE_FOR_WEB, committing, nudge}; pub use commit::{cancel, commit, end_if_left, follow_edits, intercept, is_enabled, on_job_event, track_steps}; +use cylinder::CylinderHandle; +#[cfg(test)] +use cylinder::{cylinder_cursor, cylinder_default, cylinder_dragged, cylinder_handles, cylinder_hit, cylinder_values}; #[cfg(test)] use drag_modes::{HandleIndicator, handle_indicator, keep_convex, turns}; pub(crate) use drag_modes::{apply_drag, corner_distorts, legacy_mods}; @@ -56,7 +60,7 @@ pub(crate) use options_bar::position_size_fields; #[cfg(test)] use options_bar::{ POSITION_LIMIT_PX, Parts, SCALE_LIMIT_PCT, SIZE_UNIT_KEY, SKEW_LIMIT_DEG, matching_anchor, readout, rotate_about_pivot, scale_about_pivot, scale_limit_pct, - set_size_unit, size_pct, size_shown, size_unit, warp_grid_id, + set_size_unit, size_pct, size_shown, size_unit, warp_grid_id, warp_style_options, }; pub use options_bar::{options_bar, reset_warp}; pub(crate) use pointer::{Gesture, Hit, box_hit, hit, rotate_cursor_dir}; @@ -103,6 +107,66 @@ enum WarpDrag { Point { index: usize, start: [f64; 2], pts0: Vec<[f64; 2]> }, /// Anywhere else on the grid: the surface under the pointer follows it. Surface { s: f64, t: f64, start: [f64; 2], pts0: Vec<[f64; 2]> }, + /// A cylinder's handle, or its surface (which turns the wrap); `values0` are its seven values + /// at the press (cylinder.rs). + Cylinder { handle: CylinderHandle, start: [f64; 2], values0: [f64; 7] }, +} + +/// Opens a prepared box once its job has landed (see [`Preparing`]). +type FinishPrepared = Box Result<(), String>>; + +/// A large layer's box being prepared as a job (`begin::on_prepared` opens it when it lands). +pub(crate) struct Preparing { + job: JobId, + out: Arc>>, + finish: FinishPrepared, + /// The document and layer the box is for. + layer: (DocId, LayerId), + /// The layer was made for this box (⌥⌘T's copy, a placed file): the opened session gets the + /// marker, and a box that never opens takes the layer back, as Esc would. + made: Option, +} + +/// The canvas key of an open box's preview document (`display_doc`). +pub(crate) fn preview_key(session: u64) -> u64 { + (1 << 40) + session +} + +/// Where the document under an open box differs from the document itself: the moving layer +/// (hidden, or its selected pixels lifted out) and the layers drawn over the box instead +/// ([`preview::Above`]). Kept from when the box opens until the next one, so opening, canceling +/// and committing redraw that area instead of the whole canvas. +#[derive(Clone, Copy, Debug)] +pub(crate) struct OpenArea { + pub doc: DocId, + pub key: u64, + /// The document revision the preview was built from. + pub revision: u64, + pub area: photocraft_geom::Rect, +} + +/// The canvas damage between the document and an open box's preview of it, either way, at the +/// revision the box opened on; on a commit (one revision later) also what the commit changed. +/// `None` (redraw everything) for anything else, e.g. a box that followed an edit while open. +pub(crate) fn damage( + app: &PhotocraftApp, + doc: DocId, + seen: (u64, u64), + now: (u64, u64), + last_damage: Option, +) -> Option { + let o = app.transform_area.filter(|o| o.doc == doc)?; + let opening = seen.1 == 0 && now.1 == o.key && seen.0 == o.revision && now.0 == o.revision; + let canceled = seen.1 == o.key && now.1 == 0 && seen.0 == o.revision && now.0 == o.revision; + if opening || canceled { + return Some(o.area); + } + // Committed: the box's preview, replaced by the document with the transform applied. + if seen.1 == o.key && now.1 == 0 && seen.0 == o.revision && now.0 == o.revision + 1 { + let done = last_damage?; + return Some(if done.is_empty() { o.area } else { o.area.union(&done) }); + } + None } /// Preview state that isn't serialisable: the document without the transformed pixels, and @@ -140,6 +204,11 @@ pub struct TransformPreview { committing: Option, /// Content-Aware Scale's live preview (cas_transform.rs). pub(crate) content_aware: Option, + /// While a smart object's stored warp is edited (begin.rs `preview_without_smart_warp`): + /// the texels and box of the mode the session is not in. Warp mode shows the source without + /// the warp over the warp box, Free Transform the layer's render with it over its own box; + /// leaving or re-entering Warp mode, and Undo across it, swap them. + other_texels: Option, /// A box over several layers (#6501): their composite, which `texture` holds. several: Option, } @@ -221,6 +290,25 @@ fn style_reach(doc: &Document, ids: &[LayerId]) -> i32 { reach } +/// The preview texels of the transform mode the session is not in, and the box they cover +/// ([`TransformPreview::other_texels`]). +struct OtherTexels { + texture: crate::transform_tex::PreviewTextures, + rect: [f64; 4], + quad: [[f64; 2]; 4], +} + +/// Swaps the session's texels and box with the other mode's (`t` holds the box the texels +/// cover), when there are any: the stored warp's edit shows the source without the warp, the +/// box the render with it. +fn swap_mode_texels(t: &mut TransformSession, pv: &mut TransformPreview) { + if let Some(o) = pv.other_texels.as_mut() { + std::mem::swap(&mut pv.texture, &mut o.texture); + std::mem::swap(&mut t.rect, &mut o.rect); + std::mem::swap(&mut t.quad, &mut o.quad); + } +} + /// What [`follow_edits`] needs to rebuild the preview document. #[derive(Clone, Debug)] struct Follow { diff --git a/crates/ui-egui/src/tools/transform_tool/begin.rs b/crates/ui-egui/src/tools/transform_tool/begin.rs index bcdd5a0a5f..8f2f75bba9 100644 --- a/crates/ui-egui/src/tools/transform_tool/begin.rs +++ b/crates/ui-egui/src/tools/transform_tool/begin.rs @@ -1,15 +1,18 @@ use super::commit::{cancel, commit, start_steps}; #[cfg(test)] use super::draw::texture_quad; -use super::preview::{Above, preview_image}; +use super::preview::{Above, AbovePlan, preview_image}; use super::{ - Arc, BezierMesh, CAS_ONLY_SCALES, Color32, DocId, Document, Follow, Homography, LOCKED, LayerContent, LayerId, MadeLayer, PhotocraftApp, Several, Steps, - TransformPreview, TransformSession, Warp, WarpStyle, corners, default_interpolation, json, + Arc, BezierMesh, CAS_ONLY_SCALES, Color32, DocId, Document, Follow, Homography, LOCKED, LayerContent, LayerId, MadeLayer, OtherTexels, PhotocraftApp, + Several, Steps, TransformPreview, TransformSession, Warp, WarpStyle, corners, default_interpolation, json, swap_mode_texels, }; /// Start Free Transform on the active layer (or its selected pixels), or on the targeted unlinked /// layer mask, alpha channel or Quick Mask. pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { + if app.transform_preparing.is_some() { + return Err("Free Transform is still preparing the layer".into()); + } if let Some((params, path)) = crate::vector_ui::free_transform_path(app) { return begin_path(app, ctx, params, path); } @@ -71,53 +74,192 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> // egui reports the renderer's limit in the app; offscreen harnesses only through the device. let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); // The layers covering the moving pixels draw over them instead of under them. - let above = Above::new(ctx, format!("transform-{session}-above"), &doc, id, max_side); - above.hide_in(&mut pd.layers); + let plan = AbovePlan::new(&doc, id); + plan.hide_in(&mut pd.layers); + // What the preview document changes: the moving layer and the covering layers it leaves + // out, so the canvas redraws only there (`transform_tool::damage`), not the whole document. + let canvas = doc.bounds(); + let area = std::iter::once(id) + .chain(plan.ids.iter().copied()) + .map(|l| doc.layer(l).map_or(Some(canvas), |l| photocraft_compose::change_bounds(l, canvas))) + .try_fold(photocraft_geom::Rect::EMPTY, |r, b| { + let b = b?; + Some(if r.is_empty() { + b + } else if b.is_empty() { + r + } else { + r.union(&b) + }) + }); // A style is drawn again from the pixels as the box moves them, so they are read without it. // Not for the selected part of a layer: its style belongs to that part and the rest together. let styled = lifted.is_none() && photocraft_compose::effects::has_effects(layer); - let (image, uv) = preview_image(&doc, id, lifted.as_ref(), b, max_side, styled); - let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); - app.transform_preview = Some(TransformPreview { - session, - doc: if frame_only { doc.clone() } else { Arc::new(pd) }, - texture, - opacity: layer.opacity * layer.fill_opacity, - above: (!frame_only).then_some(above), - styled: (styled && !frame_only).then(|| crate::transform_fx::StyledPreview::new(format!("transform-{session}-styled"))), - follow: Some(Follow { revision, hidden: if lifted.is_none() && !frame_only { vec![id] } else { Vec::new() }, selected: selected_now(app) }), - committing: None, - gesture: None, - warp_drag: None, - split_tool: None, - split_pointer: None, - split_placing: false, - split_quick: false, - steps: Steps::default(), - tool: app.ui.tool, - path: None, - content_aware: None, - several: None, - }); - app.ui.transform = Some(TransformSession { - session, - layer: id.0, - rect, - quad: corners(rect), - pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], - interpolation: default_interpolation(app).into(), - warp: None, - selection: false, - target: frame_only.then(|| json!({"frame": id.0})), - path: None, - made: None, - mode: Default::default(), - content_aware: None, - skew_v: 0.0, - layers: Vec::new(), - }); - start_steps(app); - Ok(()) + let opacity = layer.opacity * layer.fill_opacity; + let whole = lifted.is_none(); + // Reading the moving pixels and compositing the layers over them is the heavy part: hundreds + // of megapixels on a large canvas. Done on the UI thread, the window stopped answering for + // long enough that a Wayland compositor dropped it, so a large layer prepares as a job + // (with the jobs window's progress) and the box opens when it lands (`on_prepared`). + let big = plan_pixels(&plan).saturating_add(b.size().area()) >= PREPARE_IN_BACKGROUND_PX; + let source = doc.clone(); + let doc_id = doc.id; + let finish_ctx = ctx.clone(); + let selected = selected_now(app); + let finish = move |app: &mut PhotocraftApp, prepared: Prepared| -> Result<(), String> { + let ctx = &finish_ctx; + // The document is locked while preparing; still, never open a box on another state (or + // in another tab). The revision is read again: the job itself may have moved it on. + let Some(revision) = app.session.active().filter(|st| Arc::ptr_eq(&st.doc, &doc) && st.active_layer == Some(id)).map(|st| st.revision) else { + return Err("Free Transform: the document changed while it was preparing".into()); + }; + // Nor over a layer the Layers panel no longer has selected. + if selected_now(app) != selected { + return Err("Free Transform: the layer selection changed while it was preparing".into()); + } + let Prepared { plan, above, image: (image, uv) } = prepared; + let above = Above::from_plan(ctx, format!("transform-{session}-above"), max_side, plan, above); + app.transform_area = area.map(|area| super::OpenArea { doc: doc.id, key: super::preview_key(session), revision, area }); + let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); + app.transform_preview = Some(TransformPreview { + session, + doc: if frame_only { doc.clone() } else { Arc::new(pd) }, + texture, + opacity, + above: (!frame_only).then_some(above), + styled: (styled && !frame_only).then(|| crate::transform_fx::StyledPreview::new(format!("transform-{session}-styled"))), + follow: Some(Follow { revision, hidden: if whole && !frame_only { vec![id] } else { Vec::new() }, selected: selected_now(app) }), + committing: None, + other_texels: None, + gesture: None, + warp_drag: None, + split_tool: None, + split_pointer: None, + split_placing: false, + split_quick: false, + steps: Steps::default(), + tool: app.ui.tool, + path: None, + content_aware: None, + several: None, + }); + app.ui.transform = Some(TransformSession { + session, + layer: id.0, + rect, + quad: corners(rect), + pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], + interpolation: default_interpolation(app).into(), + warp: None, + selection: false, + target: frame_only.then(|| json!({"frame": id.0})), + path: None, + made: None, + mode: Default::default(), + content_aware: None, + skew_v: 0.0, + layers: Vec::new(), + }); + start_steps(app); + Ok(()) + }; + // `canceled` is asked between the two images, so a canceled job doesn't make the second. + let prepare = move |canceled: &dyn Fn() -> bool| -> Option { + let above = plan.image(max_side); + if canceled() { + return None; + } + Some(Prepared { above, image: preview_image(&source, id, lifted.as_ref(), b, max_side, styled), plan }) + }; + if !(big && app.background_jobs) { + let prepared = prepare(&|| false).ok_or("Free Transform: nothing was prepared")?; + return finish(app, prepared); + } + // The worker leaves its result here; the job's own result is only the jobs window's. + let out = std::sync::Arc::new(std::sync::Mutex::new(None)); + let slot = out.clone(); + let started = app + .session + .start_job( + "edit.freeTransform", + json!({}), + tl!("Preparing Free Transform"), + true, + move |job| { + job.progress(0.0, "Reading the layer"); + let prepared = prepare(&|| job.cancelled()); + job.check()?; + if let Ok(mut s) = slot.lock() { + *s = prepared; + } + Ok(()) + }, + |_, ()| Ok(json!({})), + ) + .map_err(|e| e.to_string())?; + match started { + photocraft_engine::jobs::Started::Job(job) => { + app.transform_preparing = Some(super::Preparing { job, out, finish: Box::new(finish), layer: (doc_id, id), made: None }); + Ok(()) + } + // Ran inline after all (a session without workers). + photocraft_engine::jobs::Started::Done(_) => { + let prepared = out.lock().ok().and_then(|mut o| o.take()).ok_or("Free Transform: nothing was prepared")?; + finish(app, prepared) + } + } +} + +/// A layer box whose moving and covering pixels add up to this many prepares in the background +/// (16 MP: about a 4096 × 4096 layer, a few tenths of a second to read and composite). +const PREPARE_IN_BACKGROUND_PX: u64 = 16 << 20; + +/// What a box's preview images are made from and the images themselves: the worker's result. +pub(crate) struct Prepared { + plan: AbovePlan, + above: Option<(egui::ColorImage, [f32; 2])>, + image: (egui::ColorImage, [f32; 2]), +} + +fn plan_pixels(plan: &AbovePlan) -> u64 { + plan.area() +} + +/// The preparing job of a large layer's box ended: open the box, or drop it (canceled, failed). +/// `true` when the event was that job's. +pub(crate) fn on_prepared(app: &mut PhotocraftApp, e: &photocraft_engine::jobs::JobEvent) -> bool { + if app.transform_preparing.as_ref().is_none_or(|p| p.job != e.id) { + return false; + } + let Some(p) = app.transform_preparing.take() else { return true }; + let (made, (document, layer)) = (p.made, p.layer); + let prepared = if matches!(e.outcome, photocraft_engine::jobs::JobOutcome::Done(_)) { p.out.lock().ok().and_then(|mut o| o.take()) } else { None }; + let opened = match prepared.map(|prepared| (p.finish)(app, prepared)) { + Some(Ok(())) => true, + Some(Err(err)) => { + crate::notices::error(app, err); + false + } + None => false, + }; + // As `mark_made` would have done at once, had the box opened inline. + if let Some(made) = made { + if opened && let Some(t) = app.ui.transform.as_mut() { + t.made = Some(made); + } else { + take_back_made(app, document, layer); + } + } + true +} + +/// Mark the box `begin` opened, or the one it is still preparing, as made for `made`. +fn mark_made(app: &mut PhotocraftApp, made: MadeLayer) { + if let Some(t) = app.ui.transform.as_mut() { + t.made = Some(made); + } else if let Some(p) = app.transform_preparing.as_mut() { + p.made = Some(made); + } } pub(super) fn interpolation_preference(interpolation: &str) -> Option { @@ -195,6 +337,7 @@ fn begin_several(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc Result<(), St } return Err(e); } - if let Some(t) = app.ui.transform.as_mut() { - t.made = Some(MadeLayer::Copy); - } + mark_made(app, MadeLayer::Copy); Ok(()) } @@ -301,9 +442,7 @@ pub fn begin_placed(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), return Ok(()); } begin(app, ctx)?; - if let Some(t) = app.ui.transform.as_mut() { - t.made = Some(MadeLayer::Place); - } + mark_made(app, MadeLayer::Place); Ok(()) } @@ -357,6 +496,7 @@ pub(crate) fn begin_content_aware( above: Some(above), follow: Some(Follow { revision, hidden: Vec::new(), selected: None }), committing: None, + other_texels: None, gesture: None, warp_drag: None, split_tool: None, @@ -486,6 +626,7 @@ fn begin_lone( styled: None, follow: None, committing: None, + other_texels: None, gesture: None, warp_drag: None, split_tool: None, @@ -551,6 +692,7 @@ fn begin_path(app: &mut PhotocraftApp, ctx: &egui::Context, params: serde_json:: above: None, follow: None, committing: None, + other_texels: None, several: None, }); app.ui.transform = Some(TransformSession { @@ -628,6 +770,7 @@ pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<( styled: None, follow: None, committing: None, + other_texels: None, gesture: None, warp_drag: None, split_tool: None, @@ -704,16 +847,30 @@ pub fn enter_warp(app: &mut PhotocraftApp, ctx: &egui::Context) { if t.warp.is_some() || t.target.is_some() || !t.layers.is_empty() { return; } - if t.quad == corners(t.rect) - && !t.selection - && t.path.is_none() + let untouched = t.quad == corners(t.rect) && !t.selection && t.path.is_none(); + // Back into Warp mode after leaving it: the texels and box it showed are kept. + if untouched + && let Some(w) = &existing + && let Some(pv) = app.transform_preview.as_mut() + && pv.other_texels.is_some() + { + swap_mode_texels(t, pv); + t.warp = Some(w.clone()); + return; + } + // The stored warp is edited only when the source can be previewed without it: the texels + // the box opened with have the warp in them, and the mesh would warp them again. + if untouched && let Some(w) = existing + && preview_without_smart_warp(app, ctx, w.bounds) + && let Some(t) = app.ui.transform.as_mut() { t.rect = w.bounds; t.quad = corners(w.bounds); t.warp = Some(w); return; } + let Some(t) = app.ui.transform.as_mut() else { return }; let h = Homography::rect_to_quad(t.rect, t.quad).unwrap_or(Homography::IDENTITY); let mesh = BezierMesh::identity(t.rect, 1, 1).map_points(|p| { let (x, y) = h.apply(p[0], p[1]); @@ -722,6 +879,49 @@ pub fn enter_warp(app: &mut PhotocraftApp, ctx: &egui::Context) { t.warp = Some(Warp::custom(mesh, t.rect)); } +/// Whether the active layer is warped: a Warp box is open on it, or it is a smart object with a +/// stored warp, which Edit › Transform › Warp then opens for editing (its menu item is checked). +pub fn warps_active_layer(app: &PhotocraftApp) -> bool { + if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()) { + return true; + } + let Some(st) = app.session.active() else { return false }; + st.active_layer + .and_then(|id| st.doc.layer(id)) + .is_some_and(|l| matches!(&l.content, LayerContent::Smart(sm) if sm.warp.as_ref().is_some_and(|w| !w.is_identity()))) +} + +/// The preview texels for editing a smart object's stored warp: its source placed without the +/// warp, over the warp box `r`, so the box's mesh warps it once. The texels read when the box +/// opened are the layer's render, which already has the warp: warping that again drew the +/// picture well inside the grid (#9798). Those texels and the box are kept as the other mode's +/// ([`OtherTexels`]), for leaving Warp mode. False when the source can't be re-rendered (a +/// missing linked file): the texels keep the warp, so the caller must not adopt it. +fn preview_without_smart_warp(app: &mut PhotocraftApp, ctx: &egui::Context, r: [f64; 4]) -> bool { + let (Some(t), Some(st)) = (app.ui.transform.as_ref(), app.session.active()) else { return false }; + let (id, session, box_rect, box_quad) = (LayerId(t.layer), t.session, t.rect, t.quad); + let doc = st.doc.clone(); + let Some(LayerContent::Smart(sm)) = doc.layer(id).map(|l| &l.content) else { return false }; + let mut flat = sm.clone(); + flat.warp = None; + let Ok(Some(surface)) = photocraft_engine::smart_cmds::render(&doc, &flat) else { return false }; + flat.cache = Some(surface); + let mut plain = (*doc).clone(); + if let Some(l) = plain.layer_mut(id) { + l.content = LayerContent::Smart(flat); + } + let b = photocraft_geom::Rect::new(r[0].round() as i32, r[1].round() as i32, r[2].round() as i32, r[3].round() as i32); + if b.is_empty() { + return false; + } + let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); + let Some(pv) = app.transform_preview.as_mut() else { return false }; + let (image, uv) = preview_image(&plain, id, None, b, max_side, pv.styled.is_some()); + let unwarped = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}-unwarped"), image, uv); + pv.other_texels = Some(OtherTexels { texture: std::mem::replace(&mut pv.texture, unwarped), rect: box_rect, quad: box_quad }); + true +} + /// The open transform moves an editable type layer as a whole (not a lone mask, channel, path or /// the selection). Its Warp is Warp Text: only the styles, and the type stays editable (#3004). pub fn warps_type(app: &PhotocraftApp) -> bool { @@ -790,6 +990,10 @@ fn enter_type_warp(app: &mut PhotocraftApp, ctx: &egui::Context) { pub fn leave_warp(app: &mut PhotocraftApp) { if let Some(t) = app.ui.transform.as_mut() { t.warp = None; + // A stored warp's edit showed the source without it: the box shows the render with it. + if let Some(pv) = app.transform_preview.as_mut() { + swap_mode_texels(t, pv); + } } if let Some(pv) = app.transform_preview.as_mut() { pv.split_tool = None; diff --git a/crates/ui-egui/src/tools/transform_tool/commit.rs b/crates/ui-egui/src/tools/transform_tool/commit.rs index 2f799609e9..f00382748a 100644 --- a/crates/ui-egui/src/tools/transform_tool/commit.rs +++ b/crates/ui-egui/src/tools/transform_tool/commit.rs @@ -130,6 +130,9 @@ pub(crate) fn committing(app: &PhotocraftApp) -> Option { /// A job ended (see [`crate::jobs_ui`]): when it was the commit, the session ends with it. Its /// status and errors are reported like any job's. pub fn on_job_event(app: &mut PhotocraftApp, e: &JobEvent) { + if super::begin::on_prepared(app, e) { + return; + } if committing(app) != Some(e.id) { return; } @@ -326,6 +329,9 @@ pub(crate) fn nudge(app: &mut PhotocraftApp, dx: f64, dy: f64) { /// Save for Web (Legacy): refused under an open box, as it would export without the preview (#6737). pub(crate) const SAVE_FOR_WEB: &str = "file.export.saveForWebLegacy"; +/// Layer › Copy CSS: refused under an open box too, as it would copy the bounds from before it. +const COPY_CSS: &str = photocraft_engine::layer_css_cmds::ID; + /// While transforming, Undo and Redo apply to the box: `Some(enabled)` for those commands (and /// Toggle Last State, which would change the document under the box), `None` for the rest. pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { @@ -349,7 +355,8 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { // No Toggle Last State or history jump under the box, and one box at a time. "edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" => Some(false), // Save for Web exports the committed document and would ignore the pending box (#6737). - SAVE_FOR_WEB => Some(false), + // Copy CSS, likewise, would copy the layers' bounds from before the box. + SAVE_FOR_WEB | COPY_CSS => Some(false), // Rotate and Flip turn the box (not while warping, where the mesh is the box). _ if box_preset(id).is_some() => Some(t.warp.is_none()), // One box over several layers doesn't warp (#6501). @@ -397,7 +404,8 @@ fn box_preset(id: &str) -> Option<(f64, f64, f64)> { /// `None` for other commands or when not transforming. /// The commands the open box answers itself ([`is_enabled`], [`intercept`]). fn box_command(id: &str) -> bool { - matches!(id, "edit.undo" | "edit.redo" | "edit.toggleLastState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB) || box_preset(id).is_some() + matches!(id, "edit.undo" | "edit.redo" | "edit.toggleLastState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB | COPY_CSS) + || box_preset(id).is_some() } pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option> { @@ -408,7 +416,7 @@ pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option Some(Ok(step(app, false))), "edit.redo" => Some(Ok(step(app, true))), - "edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB => { + "edit.toggleLastState" | "history.selectState" | "edit.contentAwareScale" | "edit.puppetWarp" | SAVE_FOR_WEB | COPY_CSS => { Some(Err("Commit or cancel the transform first".into())) } _ => { @@ -435,6 +443,15 @@ fn step(app: &mut PhotocraftApp, redo: bool) -> serde_json::Value { let Some(step) = from.pop() else { return serde_json::Value::Null }; to.push(Step::of(t)); s.settled = Some(step.clone()); + let (had_warp, rect, quad) = (t.warp.is_some(), t.rect, t.quad); step.restore(t); + // Across the Warp boundary, a stored warp's edit shows other texels (begin.rs): the step + // brings its own box, so only the texels swap, and the other mode keeps the box it left. + if had_warp != t.warp.is_some() + && let Some(o) = pv.other_texels.as_mut() + { + std::mem::swap(&mut pv.texture, &mut o.texture); + (o.rect, o.quad) = (rect, quad); + } json!({"transform": t}) } diff --git a/crates/ui-egui/src/tools/transform_tool/cylinder.rs b/crates/ui-egui/src/tools/transform_tool/cylinder.rs new file mode 100644 index 0000000000..7869625d2c --- /dev/null +++ b/crates/ui-egui/src/tools/transform_tool/cylinder.rs @@ -0,0 +1,262 @@ +//! Edit › Transform › Warp's Cylinder in Warp mode (#4112): the preset that wraps the contents +//! round a horizontal cylinder, for the label on a can, a jar or a bottle. Photoshop keeps it as +//! seven values rather than a mesh ([`photocraft_geom::warp::cylinder_mesh`]): the left and right +//! silhouettes, the top and bottom edges, the depth of the upper and lower ellipse (in units of +//! the half axis) and how far the contents wrap round (0..1). This is its editor: five handles +//! set those values, and the warp stays a cylinder through the commit, so a smart object keeps +//! it as `warpCylinder` in a PSD. +//! +//! The grid and the handles follow the reference application by observation (never its code), +//! as compared on #9798. The wrapped picture is outlined and cut into a 3 × 2 grid: two +//! horizontal curves and the vertical centre line, which the bend and wrap handles work from. +//! Squares at the top-right and the bottom-left corner each move their silhouette and edge +//! (the opposite corner stays put). The handle in the middle of the upper arc sets the bend of +//! both arcs (and so its own height); the one in the middle of the lower arc sets the lower +//! edge's height. The handle at the centre of the grid slides to the right, stretching the +//! middle of the picture and squeezing its sides further round the back (the wrap). A drag +//! anywhere else on the cylinder moves the whole of it. The options bar keeps Bend, H and V +//! greyed, as for a custom warp, and a cylinder has no splits and no grid menu. + +use super::warp::surface_at; +use super::{Color32, CursorIcon, PhotocraftApp, Pos2, Stroke, ToolEvent, TransformPreview, ViewXform, Warp, WarpDrag, WarpStyle, vec2}; + +/// What a press on the cylinder grabbed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum CylinderHandle { + /// A corner, clockwise from the top-left; the reference shows the top-right (1) and the + /// bottom-left (3). Its silhouette and its edge follow the pointer, the opposite corner stays. + Corner(usize), + /// The middle of the upper arc: the bend of both arcs follows it up and down. + Bend, + /// The middle of the lower arc: the lower edge follows it up and down (the height). + Bottom, + /// The centre of the grid: dragged to the right, it stretches the middle of the picture and + /// squeezes its sides round the back. + Wrap, + /// Anywhere else on the cylinder: the whole cylinder moves. + Surface, +} + +/// The bend of both arcs the Warp menu's Cylinder starts with, in units of the half axis: about +/// a quarter of the width, as the reference starts. +const DEFAULT_DEPTH: f64 = 0.5; + +/// How far the wrap handle starts along its travel from the centre: about 15 %, as the reference. +const DEFAULT_WRAP_POS: f64 = 0.15; + +/// The silhouettes never cross, nor do the edges: the moved one stops this far (document px) +/// short of the other. +const MIN_SIDE: f64 = 1.0; + +/// An arc is at most as deep as the half axis, either way up. +const DEPTH_LIMIT: f64 = 1.0; + +/// The cylinder the Warp menu's Cylinder starts with over the box `b`: its four corners on the +/// box (so the lower arc hangs below it), both arcs [`DEFAULT_DEPTH`] deep and the wrap handle +/// [`DEFAULT_WRAP_POS`] along its travel. `None` for an empty box. +pub(super) fn cylinder_default(b: [f64; 4]) -> Option { + if !(b[2] > b[0] && b[3] > b[1]) { + return None; + } + Warp::cylinder(&[b[0], b[3], b[2], b[1], DEFAULT_DEPTH, DEFAULT_DEPTH, wrap_of_pos(DEFAULT_WRAP_POS)], b) +} + +/// The seven values of `w` when it is a cylinder: left, bottom, right, top (document px), the +/// top and bottom arcs' depth (half-axis units, down is positive) and the wrap (0..1). +pub(super) fn cylinder_values(w: &Warp) -> Option<[f64; 7]> { + if w.style != WarpStyle::Cylinder { + return None; + } + w.values.as_slice().try_into().ok() +} + +/// The wrap handle's place along its travel (0 at the centre, 1 at the right silhouette) for the +/// stored wrap `g`. At `g` = 0 the model puts a sixth of the picture round the back on each side +/// with the middle stretched most, at 1 almost none: the handle slides right as the picture's +/// middle is stretched, so its travel is the wrap reversed. +fn pos_of_wrap(g: f64) -> f64 { + 1.0 - g.clamp(0.0, 1.0) +} + +/// The stored wrap for the handle's place along its travel ([`pos_of_wrap`] inverted). +fn wrap_of_pos(p: f64) -> f64 { + 1.0 - p.clamp(0.0, 1.0) +} + +/// Where the five handles are, in document space: the top-right and bottom-left corners, the +/// middle of each arc (where the mesh puts its front) and the wrap handle, on the centre line +/// midway between the arcs' fronts, [`pos_of_wrap`] of the half axis to the right of the centre. +pub(super) fn cylinder_handles(v: &[f64; 7]) -> [([f64; 2], CylinderHandle); 5] { + let [left, bottom, right, top, top_depth, bottom_depth, wrap] = *v; + let a = (right - left) / 2.0; + let cx = (left + right) / 2.0; + let (top_front, bottom_front) = (top + top_depth * a, bottom + bottom_depth * a); + [ + ([right, top], CylinderHandle::Corner(1)), + ([left, bottom], CylinderHandle::Corner(3)), + ([cx, top_front], CylinderHandle::Bend), + ([cx, bottom_front], CylinderHandle::Bottom), + ([cx + pos_of_wrap(wrap) * a, (top_front + bottom_front) / 2.0], CylinderHandle::Wrap), + ] +} + +/// The nearest handle within `tol` of `p`, else the surface when `p` is on the cylinder, else +/// `None` (off it: a press there grabs nothing). +pub(super) fn cylinder_hit(w: &Warp, p: [f64; 2], tol: f64) -> Option { + let v = cylinder_values(w)?; + let d = |q: [f64; 2]| (q[0] - p[0]).hypot(q[1] - p[1]); + let nearest = cylinder_handles(&v).into_iter().map(|(q, h)| (d(q), h)).filter(|(dist, _)| *dist < tol).min_by(|a, b| a.0.total_cmp(&b.0)); + match nearest { + Some((_, h)) => Some(h), + None => surface_at(w.mesh.as_ref()?, p).map(|_| CylinderHandle::Surface), + } +} + +/// The values after `handle` is dragged by `d` from the press, where they were `v0`. A corner +/// takes its silhouette and its edge along (the opposite corner stays put); the bend handle sets +/// both arcs' depth from where it is dragged to; the bottom handle moves the lower edge; the wrap +/// handle follows the pointer along its travel; the surface moves the whole cylinder. The +/// silhouettes and the edges keep their order, and the depth stays within the half axis. +pub(super) fn cylinder_dragged(v0: [f64; 7], handle: CylinderHandle, d: [f64; 2]) -> [f64; 7] { + let mut v = v0; + let a = ((v0[2] - v0[0]) / 2.0).max(MIN_SIDE / 2.0); + match handle { + CylinderHandle::Corner(i) => { + if i == 0 || i == 3 { + v[0] += d[0]; + } else { + v[2] += d[0]; + } + if i < 2 { + v[3] += d[1]; + } else { + v[1] += d[1]; + } + } + CylinderHandle::Bend => { + // Both arcs bend by the same amount, so a file's unequal depths keep their difference + // and a press that doesn't move changes nothing; a stored depth past the limit is + // kept as the limit rather than clamped by the press. + let step = d[1] / a; + v[4] = depth_dragged(v0[4], step); + v[5] = depth_dragged(v0[5], step); + } + CylinderHandle::Bottom => v[1] += d[1], + CylinderHandle::Wrap => v[6] = wrap_of_pos(pos_of_wrap(v0[6]) + d[0] / a), + CylinderHandle::Surface => { + v[0] += d[0]; + v[2] += d[0]; + v[1] += d[1]; + v[3] += d[1]; + } + } + // A move keeps the shape as it is, however narrow. + if handle == CylinderHandle::Surface { + return v; + } + // The silhouette or edge being moved stops just short of the other one. + if v[2] - v[0] < MIN_SIDE { + if matches!(handle, CylinderHandle::Corner(1 | 2)) { + v[2] = v[0] + MIN_SIDE; + } else { + v[0] = v[2] - MIN_SIDE; + } + } + if v[1] - v[3] < MIN_SIDE { + if matches!(handle, CylinderHandle::Corner(0 | 1)) { + v[3] = v[1] - MIN_SIDE; + } else { + v[1] = v[3] + MIN_SIDE; + } + } + v +} + +/// `depth0` moved by `step`, kept within the half axis, or within its own reach when it already +/// lies past that (a cylinder read from a file). +fn depth_dragged(depth0: f64, step: f64) -> f64 { + let limit = DEPTH_LIMIT.max(depth0.abs()); + (depth0 + step).clamp(-limit, limit) +} + +/// Pointer input on a cylinder in Warp mode: a press grabs a handle or the surface +/// ([`cylinder_hit`]), and the drag sets the values ([`cylinder_dragged`]) and rebuilds the mesh +/// from them on every move, so the preview follows. A press off the cylinder grabs nothing. +pub(super) fn cylinder_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tol: f64) { + let (Some(t), Some(pv)) = (app.ui.transform.as_mut(), app.transform_preview.as_mut()) else { return }; + let Some(w) = t.warp.as_mut() else { return }; + match ev { + ToolEvent::Down { x, y, .. } => { + pv.warp_drag = + cylinder_values(w).and_then(|values0| cylinder_hit(w, [x, y], tol).map(|handle| WarpDrag::Cylinder { handle, start: [x, y], values0 })); + } + ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => { + if let Some(WarpDrag::Cylinder { handle, start, values0 }) = &pv.warp_drag + && let Some(c) = Warp::cylinder(&cylinder_dragged(*values0, *handle, [x - start[0], y - start[1]]), w.bounds) + { + *w = c; + } + if matches!(ev, ToolEvent::Up { .. }) { + pv.warp_drag = None; + } + } + } +} + +/// The cursor over document point `p` of the cylinder `w`: a resize arrow on a handle (as the +/// view turns it), the move cursor on the surface, the plain arrow off it. +pub(super) fn cylinder_cursor(w: &Warp, p: [f64; 2], tol: f64, xf: &ViewXform) -> CursorIcon { + let Some(v) = cylinder_values(w) else { return CursorIcon::Default }; + let quad = [[v[0], v[3]], [v[2], v[3]], [v[2], v[1]], [v[0], v[1]]]; + match cylinder_hit(w, p, tol) { + Some(CylinderHandle::Corner(i)) => crate::tool_cursor::corner_resize(&quad, i, xf), + Some(CylinderHandle::Bend | CylinderHandle::Bottom) => crate::tool_cursor::resize([0.0, 1.0], xf), + Some(CylinderHandle::Wrap) => crate::tool_cursor::resize([1.0, 0.0], xf), + Some(CylinderHandle::Surface) => CursorIcon::Move, + None => CursorIcon::Default, + } +} + +/// The cylinder's outline, its 3 × 2 grid (two horizontal curves and the centre line) and its +/// handles: squares at the two corners, circles in the middle of each arc, a diamond for the +/// wrap; the one being dragged is filled with the lines' colour. `curve(u, v)` traces the mesh +/// along a fixed `u` or `v`. +pub(super) fn draw_cylinder( + painter: &egui::Painter, + w: &Warp, + curve: impl Fn(Option, Option) -> Vec, + scr: impl Fn([f64; 2]) -> Pos2, + pv: &TransformPreview, + line: Stroke, +) { + let Some(v) = cylinder_values(w) else { return }; + for u in [0.0, 0.5, 1.0] { + painter.add(egui::Shape::line(curve(Some(u), None), line)); + } + for t in [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0] { + painter.add(egui::Shape::line(curve(None, Some(t)), line)); + } + let dragged = match &pv.warp_drag { + Some(WarpDrag::Cylinder { handle, .. }) => Some(*handle), + _ => None, + }; + for (q, h) in cylinder_handles(&v) { + let p = scr(q); + let fill = if dragged == Some(h) { line.color } else { Color32::WHITE }; + match h { + CylinderHandle::Bend | CylinderHandle::Bottom => { + painter.circle_filled(p, 3.5, fill); + painter.circle_stroke(p, 3.5, line); + } + CylinderHandle::Wrap => { + let pts = vec![p - vec2(0.0, 5.0), p + vec2(5.0, 0.0), p + vec2(0.0, 5.0), p - vec2(5.0, 0.0)]; + painter.add(egui::Shape::convex_polygon(pts, fill, line)); + } + _ => { + let r = egui::Rect::from_center_size(p, vec2(7.0, 7.0)); + painter.rect_filled(r, 0.0, fill); + painter.rect_stroke(r, 0.0, line, egui::StrokeKind::Inside); + } + } + } +} diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 8205381f60..6344f8bb70 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -1,4 +1,5 @@ use super::begin::warps_type; +use super::cylinder::draw_cylinder; use super::drag_modes::{HandleIndicator, handle_indicator}; use super::options_bar::{quad_scale, readout}; use super::pointer::{Hit, handle_at, rotation_degrees}; @@ -179,7 +180,8 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform // The same keys as `cursor`, sticky ones included, so the guide matches the pointer. let mods = crate::workspace_ui::sticky_mods(app, painter.ctx().input(|i| i.modifiers)); let alt = mods.alt || mods.command; - let guide = at.filter(|_| !warps_type(app)).and_then(|p| { + // No splits on type (#3004) or a cylinder (#4112). + let guide = at.filter(|_| !warps_type(app) && w.style != WarpStyle::Cylinder).and_then(|p| { let tool = pv.split_tool.or_else(|| { (alt || pv.split_quick).then(|| { let m = w.to_mesh(1, 1); @@ -565,6 +567,12 @@ fn draw_warp_overlay(painter: &egui::Painter, xf: &ViewXform, w: &Warp, pv: &Tra }) .collect() }; + // A cylinder is outlined and cut into a 3 × 2 grid, as the reference draws it, with its own + // handles on the lines (#4112, cylinder.rs). It has no split guide. + if w.style == WarpStyle::Cylinder { + draw_cylinder(painter, w, curve, scr, pv, line); + return; + } // Patch boundaries are the grid. Only Default (one patch) draws the rule-of-thirds guides; // a 3×3 preset is three even cells, not those guides repeated inside every cell. let thirds = single_patch(&m); diff --git a/crates/ui-egui/src/tools/transform_tool/options_bar.rs b/crates/ui-egui/src/tools/transform_tool/options_bar.rs index e9ee695815..d8350ebb4a 100644 --- a/crates/ui-egui/src/tools/transform_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/transform_tool/options_bar.rs @@ -1,5 +1,6 @@ use super::begin::{enter_warp, interpolation_preference, leave_warp, warps_type}; use super::commit::{cancel, commit}; +use super::cylinder::cylinder_default; use super::pointer::point_on_quad; use super::warp::edit_session_warp; use super::{BezierMesh, Homography, PhotocraftApp, SplitTool, Stroke, TransformSession, Warp, WarpStyle, json, vec2}; @@ -464,12 +465,14 @@ fn warp_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) { }; // Type takes only the styles (#3004): Split and Grid are greyed, and there is no Custom. let on_type = warps_type(app); + // A cylinder has no splits or grid either (#4112): its handles are its own. + let cylinder = w.style == WarpStyle::Cylinder; // Split, Grid, then the warp style with its bend fields. - ui.add_enabled_ui(!on_type, |ui| warp_mesh_fields(app, ui, w)); + ui.add_enabled_ui(!on_type && !cylinder, |ui| warp_mesh_fields(app, ui, w)); crate::widgets::vline(ui, 22.0); lbl(ui, tl!("Warp:")); let mut style = w.style; - let opts: Vec<(WarpStyle, &str)> = WarpStyle::all().filter(|s| !(on_type && *s == WarpStyle::Custom)).map(|s| (s, s.label())).collect(); + let opts: Vec<(WarpStyle, &str)> = warp_style_options(on_type).map(|s| (s, s.label())).collect(); if crate::widgets::dropdown(ui, "warp-style", tl!("Warp"), &mut style, &opts, 120.0) && let Some(t) = app.ui.transform.as_mut() { @@ -478,10 +481,13 @@ fn warp_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) { WarpStyle::Custom => Warp::custom(w.to_mesh(1, 1), b), WarpStyle::None if on_type => Warp::none(b), WarpStyle::None => Warp::custom(BezierMesh::identity(b, 1, 1), b), + // The cylinder the menu starts with over the box (a box too thin for one keeps its shape). + WarpStyle::Cylinder => cylinder_default(b).unwrap_or_else(|| Warp::custom(w.to_mesh(1, 1), b)), s => Warp { style: s, bend: if w.style.is_preset() { w.bend } else { 50.0 }, ..Warp::none(b) }, }); } - // Orientation and the bend fields are always there, and only act on a preset style. + // Orientation and the bend fields are always there, and only act on a preset style (a + // cylinder keeps them greyed, as the reference does: its handles are its only controls). let preset = w.style.is_preset(); ui.add_enabled_ui(preset, |ui| { let orient = crate::icons::button(ui, "arrow-left-right", 26.0, w.vertical, tl!("Vertical")); @@ -508,6 +514,12 @@ fn warp_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) { }); } +/// The Warp menu's styles in Photoshop's order: None, Custom and the presets, then Cylinder +/// (#4112). Type takes only the styles its Warp Text has: no Custom, no Cylinder (#3004). +pub(super) fn warp_style_options(on_type: bool) -> impl Iterator { + WarpStyle::all().filter(move |s| !(on_type && *s == WarpStyle::Custom)).chain((!on_type).then_some(WarpStyle::Cylinder)) +} + /// The Split icons and the Grid menu of the Warp options bar. fn warp_mesh_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) { let tk = crate::theme::Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/tools/transform_tool/pointer.rs b/crates/ui-egui/src/tools/transform_tool/pointer.rs index 2f4d1b973f..7dbb5bb478 100644 --- a/crates/ui-egui/src/tools/transform_tool/pointer.rs +++ b/crates/ui-egui/src/tools/transform_tool/pointer.rs @@ -1,5 +1,6 @@ use super::begin::{moving_layers, warps_type}; use super::commit::{commit, committing, moves_type}; +use super::cylinder::cylinder_cursor; use super::drag_modes::{apply_drag, apply_mode_drag, drag_mods, handle_indicator, mode_allows, mode_mods}; use super::warp::{quick_split_kind, split_cursor, surface_at, warp_hit, warp_pointer}; use super::{ @@ -413,6 +414,9 @@ pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2], mods: egui::Modi if warps_type(app) { return Some(CursorIcon::Default); } + if w.style == WarpStyle::Cylinder { + return Some(cylinder_cursor(w, p, tol, xf)); + } let armed = app.transform_preview.as_ref().and_then(|pv| pv.split_tool); let quick_split = mods.alt || mods.command; if armed.is_some() || quick_split { diff --git a/crates/ui-egui/src/tools/transform_tool/preview.rs b/crates/ui-egui/src/tools/transform_tool/preview.rs index fb6db2c113..a9b34c8888 100644 --- a/crates/ui-egui/src/tools/transform_tool/preview.rs +++ b/crates/ui-egui/src/tools/transform_tool/preview.rs @@ -78,29 +78,28 @@ pub(super) struct Above { pub(super) max_side: usize, /// The covering layers (whole layers or groups, at any depth). pub(super) ids: Vec, - /// Adjustment layers over the covering ones: they stay in the document under the box as well, - /// and are composited with the covering layers so those keep the adjustment. - pub(super) applied: Vec, /// Their composite and the canvas area it covers; `None` when nothing visible covers the layer. pub(super) shown: Option<(crate::transform_tex::PreviewTextures, photocraft_geom::Rect)>, } -impl Above { - pub(super) fn new(ctx: &egui::Context, name: String, doc: &Document, id: LayerId, max_side: usize) -> Self { - let mut a = Self { ctx: ctx.clone(), name, max_side, ids: Vec::new(), applied: Vec::new(), shown: None }; - a.rebuild(doc, id); - a - } +/// What covers a layer ([`covering`]) and the document to composite it from: the cheap half of +/// [`Above`], so the composite ([`AbovePlan::image`]) can run off the UI thread. +pub(super) struct AbovePlan { + pub(super) ids: Vec, + up: Document, + rect: photocraft_geom::Rect, +} - /// Composite what covers layer `id` of `doc` (the live document) again. - pub(super) fn rebuild(&mut self, doc: &Document, id: LayerId) { - self.ids.clear(); - self.applied.clear(); - covering(&doc.layers, id, &mut self.ids, &mut self.applied); +impl AbovePlan { + pub(super) fn new(doc: &Document, id: LayerId) -> Self { + let (mut ids, mut applied) = (Vec::new(), Vec::new()); + covering(&doc.layers, id, &mut ids, &mut applied); let mut up = doc.clone(); let mut covers = doc.clone(); - show_only(&mut covers.layers, &self.ids); - let keep: Vec = self.ids.iter().chain(&self.applied).copied().collect(); + show_only(&mut covers.layers, &ids); + // Adjustment layers over the covering ones (`applied`) stay in the document under the box + // as well, and are composited with the covering layers so those keep the adjustment. + let keep: Vec = ids.iter().chain(&applied).copied().collect(); show_only(&mut up.layers, &keep); let canvas = up.bounds(); // An adjustment touches only pixels the covering layers have, so they alone bound the composite. @@ -110,22 +109,59 @@ impl Above { .filter(|l| l.visible) .fold(photocraft_geom::Rect::EMPTY, |r, l| r.union(&photocraft_compose::composite_bounds(l, canvas).unwrap_or(canvas))) .intersect(&canvas); - self.shown = (!rect.is_empty()).then(|| { - let (image, uv) = composite_image(&up, rect, self.max_side); - (crate::transform_tex::PreviewTextures::new(&self.ctx, self.name.clone(), image, uv), rect) - }); + Self { ids, up, rect } + } + + /// How many canvas pixels the covering composite spans. + pub(super) fn area(&self) -> u64 { + self.rect.size().area() + } + + /// The covering layers' composite (the heavy part; any thread). `None` when nothing covers. + pub(super) fn image(&self, max_side: usize) -> Option<(egui::ColorImage, [f32; 2])> { + (!self.rect.is_empty()).then(|| composite_image(&self.up, self.rect, max_side)) } /// Leave the covering layers out of `layers` (the document under the box). pub(super) fn hide_in(&self, layers: &mut [photocraft_doc::Layer]) { - for l in layers.iter_mut() { - if self.ids.contains(&l.id) { - l.visible = false; - } else if let LayerContent::Group(g) = &mut l.content { - self.hide_in(&mut g.children); - } + hide_ids(&self.ids, layers); + } +} + +fn hide_ids(ids: &[LayerId], layers: &mut [photocraft_doc::Layer]) { + for l in layers.iter_mut() { + if ids.contains(&l.id) { + l.visible = false; + } else if let LayerContent::Group(g) = &mut l.content { + hide_ids(ids, &mut g.children); } } +} + +impl Above { + pub(super) fn new(ctx: &egui::Context, name: String, doc: &Document, id: LayerId, max_side: usize) -> Self { + let plan = AbovePlan::new(doc, id); + let image = plan.image(max_side); + Self::from_plan(ctx, name, max_side, plan, image) + } + + /// An `Above` from its plan and the composite made from it (on the UI thread: textures). + pub(super) fn from_plan(ctx: &egui::Context, name: String, max_side: usize, plan: AbovePlan, image: Option<(egui::ColorImage, [f32; 2])>) -> Self { + let shown = image.map(|(image, uv)| (crate::transform_tex::PreviewTextures::new(ctx, name.clone(), image, uv), plan.rect)); + Self { ctx: ctx.clone(), name, max_side, ids: plan.ids, shown } + } + + /// Composite what covers layer `id` of `doc` (the live document) again. + pub(super) fn rebuild(&mut self, doc: &Document, id: LayerId) { + let plan = AbovePlan::new(doc, id); + let image = plan.image(self.max_side); + *self = Self::from_plan(&self.ctx.clone(), self.name.clone(), self.max_side, plan, image); + } + + /// Leave the covering layers out of `layers` (the document under the box). + pub(super) fn hide_in(&self, layers: &mut [photocraft_doc::Layer]) { + hide_ids(&self.ids, layers); + } /// Draw the composite over the moving pixels. pub(super) fn draw(&self, painter: &egui::Painter, xf: &ViewXform, display: Option<&photocraft_engine::display_color::CanvasDisplay>) { diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index 08d24d6607..a3e48f20ed 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -1148,6 +1148,47 @@ fn save_for_web_is_off_under_a_pending_transform() { assert!(crate::menus::is_enabled(&app, SAVE_FOR_WEB), "back after the box closes"); } +/// Layer › Copy CSS reads the committed document, so, as Save for Web (#6737), it is off while a +/// box is pending: the clipboard never gets the bounds from before the move. After Cancel it +/// copies the old place, after a commit the new one. +#[test] +fn copy_css_is_off_under_a_pending_transform() { + let id = photocraft_engine::layer_css_cmds::ID; + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let copy_css = |app: &mut PhotocraftApp| { + let mut result = None; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| result = Some(crate::menus::invoke(app, ui.ctx(), id, json!({})))); + out.textures_delta.clear(); + (result.unwrap(), out.platform_output.commands) + }; + let moved = |app: &mut PhotocraftApp| { + crate::menus::invoke(app, &egui::Context::default(), "edit.freeTransform", json!({})).unwrap(); + let t = app.ui.transform.as_mut().unwrap(); + t.quad = t.quad.map(|[x, y]| [x + 20.0, y]); + }; + assert!(crate::menus::is_enabled(&app, id), "enabled with no box"); + moved(&mut app); + assert!(!crate::menus::is_enabled(&app, id), "off under the box"); + let (result, clipboard) = copy_css(&mut app); + assert!(result.is_err(), "refused under the box: {result:?}"); + assert!(clipboard.is_empty(), "nothing reaches the clipboard: {clipboard:?}"); + assert!(app.ui.transform.is_some(), "the box stays open"); + cancel(&mut app); + assert!(crate::menus::is_enabled(&app, id), "back after Cancel"); + let (result, clipboard) = copy_css(&mut app); + let css = result.unwrap()["css"].as_str().unwrap().to_string(); + assert!(css.contains("left: 8px;"), "{css}"); + assert_eq!(clipboard, [egui::OutputCommand::CopyText(css)]); + moved(&mut app); + commit(&mut app); + assert!(app.ui.transform.is_none() && crate::menus::is_enabled(&app, id), "back after the commit"); + let (result, clipboard) = copy_css(&mut app); + let css = result.unwrap()["css"].as_str().unwrap().to_string(); + assert!(css.contains("left: 28px;"), "the moved place: {css}"); + assert_eq!(clipboard, [egui::OutputCommand::CopyText(css)]); +} + /// #352: ⌥⌘T transforms a copy. OK leaves the original and a moved copy as one history step; /// Cancel leaves no copy and nothing to redo; with a selection the copy holds the selected /// pixels only. @@ -2336,7 +2377,7 @@ fn plain_layers_from_the_top_cover_the_moving_one() { assert_eq!(covers(&layers, c), [tp, inner], "a clipped layer: covered by what is over its clipping group"); // Under the box, the covering layers leave the document; over it, they alone show. - let above = Above { ctx: egui::Context::default(), name: String::new(), max_side: 64, ids: vec![tp, inner], applied: Vec::new(), shown: None }; + let above = Above { ctx: egui::Context::default(), name: String::new(), max_side: 64, ids: vec![tp, inner], shown: None }; let mut under = layers.clone(); above.hide_in(&mut under); let vis = |ls: &[Layer]| [ls[0].visible, ls[1].visible, ls[2].visible]; @@ -3666,6 +3707,325 @@ fn applying_the_box_hides_no_pointer() { assert_eq!(cursor(&app, &xf, [96.0, 32.0], cmd()), Some(CursorIcon::ResizeVertical)); } +// ---- Cylinder (#4112) ---- + +fn cylinder_of(app: &PhotocraftApp) -> [f64; 7] { + cylinder_values(app.ui.transform.as_ref().unwrap().warp.as_ref().unwrap()).unwrap() +} + +/// The Warp menu lists Cylinder after the presets, for everything but type (Warp Text has none). +#[test] +fn the_warp_menu_lists_cylinder_after_the_presets_except_on_type() { + let all: Vec = warp_style_options(false).collect(); + assert_eq!(all.last(), Some(&WarpStyle::Cylinder)); + assert_eq!(all.len(), WarpStyle::all().count() + 1); + assert!(all.contains(&WarpStyle::Custom) && all.contains(&WarpStyle::Twist)); + let on_type: Vec = warp_style_options(true).collect(); + assert!(!on_type.contains(&WarpStyle::Cylinder) && !on_type.contains(&WarpStyle::Custom)); + assert!(on_type.contains(&WarpStyle::None) && on_type.contains(&WarpStyle::Arc)); +} + +/// The cylinder the menu starts with, as the reference starts it: its four corners on the box, +/// both arcs half the half axis deep (a quarter of the width), so the lower one hangs below the +/// box, and the wrap handle 15 % along its travel. +#[test] +fn the_warp_menus_cylinder_starts_on_the_box_corners() { + let b = [8.0, 8.0, 32.0, 32.0]; + let w = cylinder_default(b).unwrap(); + assert_eq!(w.style, WarpStyle::Cylinder); + let v = cylinder_values(&w).unwrap(); + assert_eq!(&v[..6], &[8.0, 32.0, 32.0, 8.0, 0.5, 0.5]); + assert!((v[6] - 0.85).abs() < 1e-9, "{v:?}"); + let wrap = cylinder_handles(&v)[4].0; + assert!((wrap[0] - (20.0 + 0.15 * 12.0)).abs() < 1e-9, "the wrap handle starts 15 % of the half axis right of the centre: {wrap:?}"); + let cb = w.mesh.as_ref().unwrap().control_bounds(); + assert!(cb[0] >= 8.0 - 1e-9 && cb[2] <= 32.0 + 1e-9 && cb[1] >= 8.0 - 1e-9, "{cb:?}"); + assert!(cb[3] > 32.0 + 5.0, "the lower arc's front hangs about 6 px below the box: {cb:?}"); + assert!(cylinder_default([0.0, 0.0, 0.0, 20.0]).is_none() && cylinder_default([0.0, 0.0, 20.0, 0.0]).is_none()); + assert!(cylinder_values(&Warp::preset(WarpStyle::Arc, 50.0, b)).is_none(), "only a cylinder has values"); +} + +/// Five handles, as the reference shows: the top-right and bottom-left corners, the middle of +/// each arc, and the wrap handle at the grid's centre, which slides right as the wrap goes down. +#[test] +fn cylinder_handles_are_two_corners_the_arcs_and_the_wrap() { + let v = [10.0, 40.0, 60.0, 10.0, 0.3, 0.2, 0.5]; + let h = cylinder_handles(&v); + assert_eq!(h[0], ([60.0, 10.0], CylinderHandle::Corner(1))); + assert_eq!(h[1], ([10.0, 40.0], CylinderHandle::Corner(3))); + assert_eq!(h[2], ([35.0, 17.5], CylinderHandle::Bend)); + assert_eq!(h[3], ([35.0, 45.0], CylinderHandle::Bottom)); + assert_eq!(h[4], ([35.0 + 0.5 * 25.0, 31.25], CylinderHandle::Wrap), "midway between the arcs' fronts, half way along at wrap 0.5"); + assert_eq!(cylinder_handles(&[10.0, 40.0, 60.0, 10.0, 0.3, 0.2, 1.0])[4].0, [35.0, 31.25], "at the centre at wrap 1"); + assert_eq!(cylinder_handles(&[10.0, 40.0, 60.0, 10.0, 0.3, 0.2, 0.0])[4].0, [60.0, 31.25], "at the silhouette at wrap 0"); + assert!(!h.iter().any(|(_, k)| matches!(k, CylinderHandle::Corner(0 | 2))), "no top-left or bottom-right corner"); + // The arc handles sit where the mesh puts the front of each arc. + let w = Warp::cylinder(&v, [10.0, 10.0, 60.0, 40.0]).unwrap(); + let m = w.mesh.clone().unwrap(); + let front_top = m.eval(0.5, 0.0); + assert!((front_top[0] - 35.0).abs() < 1e-9 && (front_top[1] - 17.5).abs() < 1e-9, "{front_top:?}"); + assert!((m.eval(0.5, 1.0)[1] - 45.0).abs() < 1e-9); + // A press: the nearest handle within reach, else the surface, else nothing. + assert_eq!(cylinder_hit(&w, [60.5, 10.5], 3.0), Some(CylinderHandle::Corner(1))); + assert_eq!(cylinder_hit(&w, [10.5, 39.0], 3.0), Some(CylinderHandle::Corner(3))); + assert_eq!(cylinder_hit(&w, [35.0, 18.0], 3.0), Some(CylinderHandle::Bend)); + assert_eq!(cylinder_hit(&w, [35.0, 44.0], 3.0), Some(CylinderHandle::Bottom)); + assert_eq!(cylinder_hit(&w, [47.0, 31.0], 3.0), Some(CylinderHandle::Wrap)); + assert_eq!(cylinder_hit(&w, [11.0, 11.0], 3.0), Some(CylinderHandle::Surface), "the top-left corner is just surface"); + assert_eq!(cylinder_hit(&w, [20.0, 30.0], 3.0), Some(CylinderHandle::Surface)); + assert_eq!(cylinder_hit(&w, [90.0, 90.0], 3.0), None); + assert_eq!(cylinder_hit(&Warp::custom(m, w.bounds), [60.5, 10.5], 3.0), None, "only a cylinder has these handles"); +} + +#[test] +fn cylinder_drags_set_its_values_and_keep_them_sound() { + let v = [10.0, 40.0, 60.0, 10.0, 0.3, 0.3, 0.5]; + // A corner takes its silhouette and its edge along; the opposite corner stays put. + assert_eq!(cylinder_dragged(v, CylinderHandle::Corner(1), [2.0, 3.0]), [10.0, 40.0, 62.0, 13.0, 0.3, 0.3, 0.5]); + assert_eq!(cylinder_dragged(v, CylinderHandle::Corner(3), [-2.0, 3.0]), [8.0, 43.0, 60.0, 10.0, 0.3, 0.3, 0.5]); + // The bend handle follows the pointer and bends both arcs: 5 px down on a 25 px half axis + // is 0.2 deeper. + let d = cylinder_dragged(v, CylinderHandle::Bend, [0.0, 5.0]); + assert!((d[4] - 0.5).abs() < 1e-9 && (d[5] - 0.5).abs() < 1e-9, "{d:?}"); + assert_eq!(&cylinder_dragged(v, CylinderHandle::Bend, [0.0, -100.0])[4..6], &[-1.0, -1.0], "clamped to the half axis"); + // Unequal depths from a file keep their difference, and a press that doesn't move keeps a + // depth past the limit as it is. + let file = [10.0, 40.0, 60.0, 10.0, 1.4, 0.2, 0.5]; + assert_eq!(cylinder_dragged(file, CylinderHandle::Bend, [0.0, 0.0]), file); + let d = cylinder_dragged(file, CylinderHandle::Bend, [0.0, -5.0]); + assert!((d[4] - 1.2).abs() < 1e-9 && (d[5] - 0.0).abs() < 1e-9, "{d:?}"); + assert_eq!(cylinder_dragged(file, CylinderHandle::Bend, [0.0, 50.0])[4], 1.4, "no further than it already reaches"); + // A move keeps the shape, however narrow the cylinder. + let narrow = [10.0, 40.0, 10.5, 10.0, 0.3, 0.3, 0.5]; + assert_eq!(cylinder_dragged(narrow, CylinderHandle::Surface, [5.0, 0.0]), [15.0, 40.0, 15.5, 10.0, 0.3, 0.3, 0.5]); + // The bottom handle moves the lower edge; the arc keeps its depth. + assert_eq!(cylinder_dragged(v, CylinderHandle::Bottom, [7.0, 6.0]), [10.0, 46.0, 60.0, 10.0, 0.3, 0.3, 0.5]); + // The wrap handle follows the pointer along the half axis: right stretches the middle (wrap down). + let d = cylinder_dragged(v, CylinderHandle::Wrap, [6.25, 0.0]); + assert!((d[6] - 0.25).abs() < 1e-9, "{d:?}"); + assert_eq!(cylinder_dragged(v, CylinderHandle::Wrap, [80.0, 0.0])[6], 0.0); + assert_eq!(cylinder_dragged(v, CylinderHandle::Wrap, [-80.0, 0.0])[6], 1.0); + // The surface moves the whole cylinder. + assert_eq!(cylinder_dragged(v, CylinderHandle::Surface, [5.0, -4.0]), [15.0, 36.0, 65.0, 6.0, 0.3, 0.3, 0.5]); + // The silhouettes never cross, nor do the edges: the one dragged stops just short of the other. + let d = cylinder_dragged(v, CylinderHandle::Corner(3), [70.0, -50.0]); + assert_eq!([d[0], d[2], d[1], d[3]], [59.0, 60.0, 11.0, 10.0]); + let d = cylinder_dragged(v, CylinderHandle::Corner(1), [-80.0, 60.0]); + assert_eq!([d[0], d[2], d[1], d[3]], [10.0, 11.0, 40.0, 39.0]); + assert_eq!(cylinder_dragged(v, CylinderHandle::Bottom, [0.0, -80.0])[1], 11.0); + // Whatever the drag, the result is a cylinder the geometry accepts. + for h in [CylinderHandle::Corner(1), CylinderHandle::Corner(3), CylinderHandle::Bend, CylinderHandle::Bottom, CylinderHandle::Wrap, CylinderHandle::Surface] + { + assert!(Warp::cylinder(&cylinder_dragged(v, h, [-70.0, 30.0]), [10.0, 10.0, 60.0, 40.0]).is_some(), "{h:?}"); + } +} + +/// In Warp mode a cylinder's handles drag its values and the preview follows; Undo steps back +/// through the drags; Enter commits the cylinder, which a smart object keeps as one with the +/// dragged values, and Warp mode shows it again as a cylinder, whose untouched commit is no step. +#[test] +fn warp_mode_drags_a_cylinders_handles_and_commits_it_as_a_cylinder() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32)); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + begin_warp(&mut app, &ctx).unwrap(); + let b = app.ui.transform.as_ref().unwrap().rect; + app.ui.transform.as_mut().unwrap().warp = Some(cylinder_default(b).unwrap()); + track_steps(&mut app, &ctx); + let v0 = cylinder_of(&app); + let mods = egui::Modifiers::NONE; + // The bend handle, dragged 3 px down (a quarter of the 12 px half axis): both arcs bend more. + let bend = cylinder_handles(&v0)[2].0; + warp_pointer(&mut app, ToolEvent::Down { x: bend[0], y: bend[1], pressure: 1.0 }, 2.0, mods); + assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Cylinder { handle: CylinderHandle::Bend, .. }))); + warp_pointer(&mut app, ToolEvent::Move { x: bend[0], y: bend[1] + 3.0, pressure: 1.0 }, 2.0, mods); + let v = cylinder_of(&app); + assert!((v[4] - (v0[4] + 0.25)).abs() < 1e-9 && (v[5] - (v0[5] + 0.25)).abs() < 1e-9, "{v:?}"); + // The preview is the mesh of the new values, and the warp is still a cylinder. + let w = app.ui.transform.as_ref().unwrap().warp.clone().unwrap(); + assert_eq!(w.style, WarpStyle::Cylinder); + assert_eq!(w.mesh, Warp::cylinder(&v, b).unwrap().mesh); + assert!(w.mesh != Warp::cylinder(&v0, b).unwrap().mesh); + warp_pointer(&mut app, ToolEvent::Up { x: bend[0], y: bend[1] + 3.0 }, 2.0, mods); + assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none()); + track_steps(&mut app, &ctx); + // The wrap handle, dragged 3 px right: a quarter of the 12 px half axis further along. + let wrap = cylinder_handles(&cylinder_of(&app))[4].0; + warp_pointer(&mut app, ToolEvent::Down { x: wrap[0], y: wrap[1], pressure: 1.0 }, 2.0, mods); + assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Cylinder { handle: CylinderHandle::Wrap, .. }))); + warp_pointer(&mut app, ToolEvent::Up { x: wrap[0] + 3.0, y: wrap[1] }, 2.0, mods); + assert!((cylinder_of(&app)[6] - 0.6).abs() < 1e-9, "{:?}", cylinder_of(&app)); + assert!((cylinder_handles(&cylinder_of(&app))[4].0[0] - (wrap[0] + 3.0)).abs() < 1e-9, "the wrap handle followed the pointer"); + track_steps(&mut app, &ctx); + // A drag on the surface moves the whole cylinder. + let before = cylinder_of(&app); + warp_pointer(&mut app, ToolEvent::Down { x: 14.0, y: 20.0, pressure: 1.0 }, 2.0, mods); + assert!(matches!(app.transform_preview.as_ref().unwrap().warp_drag, Some(WarpDrag::Cylinder { handle: CylinderHandle::Surface, .. }))); + warp_pointer(&mut app, ToolEvent::Up { x: 18.0, y: 22.0 }, 2.0, mods); + let moved = cylinder_of(&app); + assert_eq!([moved[0] - before[0], moved[2] - before[2], moved[1] - before[1], moved[3] - before[3]], [4.0, 4.0, 2.0, 2.0], "{moved:?}"); + assert_eq!(&moved[4..], &before[4..], "the shape is unchanged"); + track_steps(&mut app, &ctx); + // A press off the cylinder grabs nothing. + warp_pointer(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, 2.0, mods); + assert!(app.transform_preview.as_ref().unwrap().warp_drag.is_none()); + warp_pointer(&mut app, ToolEvent::Up { x: 50.0, y: 50.0 }, 2.0, mods); + // Undo and Redo step through the drags inside the session. + let _ = intercept(&mut app, "edit.undo"); + assert_eq!(cylinder_of(&app), before, "undo takes back the move"); + let _ = intercept(&mut app, "edit.undo"); + assert!((cylinder_of(&app)[6] - 0.85).abs() < 1e-9, "undo takes back the wrap: {:?}", cylinder_of(&app)); + let _ = intercept(&mut app, "edit.redo"); + assert!((cylinder_of(&app)[6] - 0.6).abs() < 1e-9, "redo: {:?}", cylinder_of(&app)); + let v = cylinder_of(&app); + let steps = app.session.active().unwrap().history.past_len(); + commit(&mut app); + assert!(app.ui.transform.is_none(), "{}", app.ui.status); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps + 1, "one step"); + let photocraft_doc::LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("smart") }; + assert_eq!(sm.warp.as_ref().map(|w| w.style), Some(WarpStyle::Cylinder), "the smart object keeps a cylinder"); + // Warp mode shows the same cylinder again, with its values, and Enter changes nothing. + begin_warp(&mut app, &ctx).unwrap(); + let shown = app.ui.transform.as_ref().unwrap().warp.clone().unwrap(); + assert_eq!(shown.style, WarpStyle::Cylinder); + for (a, b) in cylinder_values(&shown).unwrap().iter().zip(&v) { + assert!((a - b).abs() < 1e-6, "{shown:?} vs {v:?}"); + } + let steps = app.session.active().unwrap().history.past_len(); + commit(&mut app); + assert!(app.ui.transform.is_none(), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "untouched: no step"); +} + +/// Warp mode on a smart object that already has a warp previews the source placed without it, +/// over the warp box, so the mesh warps the picture once and it sits on the grid (#9798). The +/// texels read when the box opened were the warped render, taller than the box by the lower +/// arc's bulge; warping them again put the picture well inside the lines. +#[test] +fn warp_mode_previews_a_stored_smart_warp_from_the_unwarped_source() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32)); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.run("layer.smartObjects.warp", json!({"style": "cylinder", "values": [8, 32, 32, 8, 0.5, 0.5, 0.85], "rect": [8, 8, 32, 32]})).unwrap(); + // The warped render reaches below the box. + let st = app.session.active().unwrap(); + let warped = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); + assert!(warped.y1 > 36, "{warped:?}"); + begin_warp(&mut app, &ctx).unwrap(); + let t = app.ui.transform.as_ref().unwrap(); + assert_eq!(t.rect, [8.0, 8.0, 32.0, 32.0]); + assert_eq!(t.warp.as_ref().map(|w| w.style), Some(WarpStyle::Cylinder)); + let (img, _) = app.transform_preview.as_ref().unwrap().texture.level_image(0).unwrap(); + assert_eq!(img.size, [24, 24], "the texels cover the box, not the warped render"); + // Opaque to its corners: the flat square, not the cylinder's shape (whose corners are clear). + for (x, y) in [(0, 0), (23, 0), (0, 23), (23, 23), (12, 12)] { + assert_eq!(img.pixels[y * 24 + x].a(), 255, "texel {x},{y}"); + } +} + +/// Leaving Warp mode, and Undo back into Free Transform, show the render with the stored warp +/// again (the texels the box opened with), and re-entering shows the source without it (#9798). +#[test] +fn leaving_warp_mode_restores_the_stored_warps_render() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32)); + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.run("layer.smartObjects.warp", json!({"style": "cylinder", "values": [8, 32, 32, 8, 0.5, 0.5, 0.85], "rect": [8, 8, 32, 32]})).unwrap(); + begin(&mut app, &ctx).unwrap(); + let texels = |app: &PhotocraftApp| app.transform_preview.as_ref().unwrap().texture.level_image(0).unwrap().0.size; + let rect = |app: &PhotocraftApp| app.ui.transform.as_ref().unwrap().rect; + let (warped, box0) = (texels(&app), rect(&app)); + assert!(warped[1] > 24 && box0[3] > 32.0, "the render with the warp hangs below the box: {warped:?} {box0:?}"); + enter_warp(&mut app, &ctx); + track_steps(&mut app, &ctx); + assert_eq!((texels(&app), rect(&app)), ([24, 24], [8.0, 8.0, 32.0, 32.0]), "the source over the warp box"); + leave_warp(&mut app); + track_steps(&mut app, &ctx); + assert!(app.ui.transform.as_ref().unwrap().warp.is_none()); + assert_eq!((texels(&app), rect(&app)), (warped, box0), "back to the render with the warp"); + enter_warp(&mut app, &ctx); + track_steps(&mut app, &ctx); + assert_eq!((texels(&app), rect(&app)), ([24, 24], [8.0, 8.0, 32.0, 32.0]), "and back again, without a re-render"); + let _ = intercept(&mut app, "edit.undo"); + assert!(app.ui.transform.as_ref().unwrap().warp.is_none()); + assert_eq!((texels(&app), rect(&app)), (warped, box0), "undo into Free Transform"); + let _ = intercept(&mut app, "edit.redo"); + assert_eq!((texels(&app), rect(&app)), ([24, 24], [8.0, 8.0, 32.0, 32.0]), "redo into Warp"); + leave_warp(&mut app); + assert_eq!((texels(&app), rect(&app)), (warped, box0), "leaving after a redo"); +} + +/// A cylinder on a pixel layer commits as previewed: the pixels wrap round between the +/// silhouettes and the ones on the back are hidden. +#[test] +fn a_cylinder_commits_the_wrapped_pixels() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 32, 32)); + begin_warp(&mut app, &egui::Context::default()).unwrap(); + let b = app.ui.transform.as_ref().unwrap().rect; + // Silhouettes pulled in to x 12..28: the square's outer columns go round the back. + let w = Warp::cylinder(&[12.0, 29.0, 28.0, 8.0, 0.25, 0.25, 0.5], b).unwrap(); + app.ui.transform.as_mut().unwrap().warp = Some(w.clone()); + commit(&mut app); + assert!(app.ui.transform.is_none(), "{}", app.ui.status); + let st = app.session.active().unwrap(); + let s = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let alpha = |x: i32, y: i32| { + let mut p = [0.0f32; 4]; + s.read_pixel(x, y, &mut p); + p[3] + }; + assert!(alpha(20, 20) > 0.99, "the front is covered: {}", alpha(20, 20)); + assert!(alpha(9, 20) < 0.01 && alpha(31, 20) < 0.01, "nothing outside the silhouettes: {} {}", alpha(9, 20), alpha(31, 20)); + // The upper arc's front dips below the top edge at the centre, so the top row there is clear. + assert!(alpha(20, 9) < 0.2, "the top bows down in the middle: {}", alpha(20, 9)); + assert!(alpha(13, 9) > 0.5, "and stays up at the silhouettes: {}", alpha(13, 9)); +} + +#[test] +fn cylinder_cursors_point_along_their_handles() { + let w = Warp::cylinder(&[10.0, 40.0, 60.0, 10.0, 0.3, 0.3, 0.5], [10.0, 10.0, 60.0, 40.0]).unwrap(); + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let level = ViewXform { rect: screen, zoom: 1.0, center: [35.0, 25.0], flip: false, rotation: 0.0, aspect: 1.0 }; + assert_eq!(cylinder_cursor(&w, [60.0, 10.0], 3.0, &level), CursorIcon::ResizeNeSw); + assert_eq!(cylinder_cursor(&w, [10.0, 40.0], 3.0, &level), CursorIcon::ResizeNeSw); + assert_eq!(cylinder_cursor(&w, [35.0, 17.5], 3.0, &level), CursorIcon::ResizeVertical); + assert_eq!(cylinder_cursor(&w, [35.0, 47.5], 3.0, &level), CursorIcon::ResizeVertical); + let wrap = cylinder_handles(&cylinder_values(&w).unwrap())[4].0; + assert_eq!(cylinder_cursor(&w, wrap, 3.0, &level), CursorIcon::ResizeHorizontal); + assert_eq!(cylinder_cursor(&w, [20.0, 30.0], 3.0, &level), CursorIcon::Move); + assert_eq!(cylinder_cursor(&w, [90.0, 90.0], 3.0, &level), CursorIcon::Default); + // The arrows turn with the view. + let turned = ViewXform { rotation: 90.0, ..level }; + assert_eq!(cylinder_cursor(&w, wrap, 3.0, &turned), CursorIcon::ResizeVertical); + assert_eq!(cylinder_cursor(&w, [35.0, 17.5], 3.0, &turned), CursorIcon::ResizeHorizontal); + // Through the transform tool's cursor, a cylinder is never a split: its surface moves it. + let mut app = app_with_square(128, photocraft_geom::Rect::new(8, 8, 104, 104)); + begin_warp(&mut app, &egui::Context::default()).unwrap(); + let b = app.ui.transform.as_ref().unwrap().rect; + app.ui.transform.as_mut().unwrap().warp = Some(cylinder_default(b).unwrap()); + app.transform_preview.as_mut().unwrap().split_tool = Some(SplitTool::Cross); + let xf = ViewXform { center: [56.0, 56.0], ..level }; + assert_eq!(cursor(&app, &xf, [30.0, 56.0], cmd()), Some(CursorIcon::Move)); +} + +/// The Warp bar keeps Bend, H and V for a cylinder, greyed like Split, Grid and the orientation +/// switch: its handles are its only controls, as in the reference. +#[test] +fn the_warp_bar_greys_its_fields_for_a_cylinder() { + use egui_kittest::kittest::{NodeT, Queryable}; + let h = bar_harness(|app| { + let t = app.ui.transform.as_mut().unwrap(); + t.warp = Some(cylinder_default(t.rect).unwrap()); + }); + // A field's caption and the field itself share the label: every match is greyed. + for name in ["Bend:", "H:", "V:", "Split Warp Crosswise", "Change warp orientation"] { + let nodes: Vec<_> = h.get_all_by_label(name).collect(); + assert!(!nodes.is_empty() && nodes.iter().all(|n| n.accesskit_node().is_disabled()), "{name} is greyed"); + } + assert!(h.query_by_label("Top depth").is_none() && h.query_by_label("Wrap").is_none(), "no cylinder fields"); +} + #[test] fn several_layers_reuse_the_transform_interpolation_preference() { let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); diff --git a/crates/ui-egui/src/tools/transform_tool/warp.rs b/crates/ui-egui/src/tools/transform_tool/warp.rs index ca918d5d06..cc882ea64c 100644 --- a/crates/ui-egui/src/tools/transform_tool/warp.rs +++ b/crates/ui-egui/src/tools/transform_tool/warp.rs @@ -1,4 +1,5 @@ use super::begin::warps_type; +use super::cylinder::cylinder_pointer; use super::{BezierMesh, CursorIcon, PhotocraftApp, SplitTool, ToolEvent, ViewXform, Warp, WarpDrag, WarpStyle, json}; /// An anchor or a handle on a section line. The inner control points of a patch are not shown. @@ -121,6 +122,10 @@ pub(super) fn warp_pointer(app: &mut PhotocraftApp, ev: ToolEvent, tol: f64, mod if warps_type(app) { return; } + // A cylinder has its own handles, and no splits (#4112). + if app.ui.transform.as_ref().and_then(|t| t.warp.as_ref()).is_some_and(|w| w.style == WarpStyle::Cylinder) { + return cylinder_pointer(app, ev, tol); + } if split_gesture(app, ev, mods) { return; } diff --git a/crates/ui-egui/src/tools/type_tool.rs b/crates/ui-egui/src/tools/type_tool.rs index 42ad346f61..60dbb231ed 100644 --- a/crates/ui-egui/src/tools/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -130,19 +130,33 @@ fn byte_range(text: &str, a: usize, b: usize) -> (usize, usize) { (at(a.min(b)), at(a.max(b))) } +#[cfg(test)] +mod vertical_align_buttons_tests; + #[cfg(test)] mod canvas_tests; +#[cfg(test)] +mod ctrl_period_cancel_tests; #[cfg(test)] mod font_commit_tests; #[cfg(test)] mod font_picker_tests; +#[cfg(test)] +mod options_tooltips_tests; #[cfg(test)] mod tests; +#[cfg(test)] +mod mask_replace_selection_tests; + #[cfg(test)] mod commit_tests; +#[cfg(test)] +mod locked_layer_alert_tests; #[cfg(test)] mod ime_tests; +#[cfg(test)] +mod mask_escape_tests; diff --git a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs index 091a0a22cb..435db44e59 100644 --- a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs @@ -795,25 +795,26 @@ fn options_bar_t_icon_scrub_stops_at_the_size_limits() { } /// Rests the pointer on the widget named `label` past the tooltip delay; true when its tooltip -/// (a second node with the same name) shows. -fn tooltip_shows(h: &mut Harness<'static, PhotocraftApp>, role: egui::accesskit::Role, label: &str) -> bool { +/// `tip` shows (one more node with that text). +fn tooltip_shows(h: &mut Harness<'static, PhotocraftApp>, role: egui::accesskit::Role, label: &str, tip: &str) -> bool { + let before = h.query_all_by_label(tip).count(); let at = h.get_by_role_and_label(role, label).rect().center(); h.hover_at(at); h.run_steps(8); - h.query_all_by_label(label).count() == 2 + h.query_all_by_label(tip).count() == before + 1 } -/// The scrubby "T" icon keeps its "Font size" tooltip: the size field's drag area, laid over the -/// icon after it, must not take its hover. +/// The scrubby "T" icon keeps its tooltip ("Set font size", #12057): the size field's drag area, +/// laid over the icon after it, must not take its hover. #[test] fn options_bar_t_icon_shows_its_tooltip() { let mut app = new_app(); app.run("type.create", json!({"text": "Hello", "size": 20, "x": 300, "y": 420})).unwrap(); let mut h = options_harness(app); - assert!(tooltip_shows(&mut h, egui::accesskit::Role::Button, "Set the text color"), "the probe sees an ordinary tooltip"); + assert!(tooltip_shows(&mut h, egui::accesskit::Role::Button, "Set the text color", "Set text color"), "the probe sees an ordinary tooltip"); h.hover_at(egui::pos2(890.0, 55.0)); h.run_steps(4); - assert!(tooltip_shows(&mut h, egui::accesskit::Role::Label, "Font size"), "hovering the \"T\" icon shows \"Font size\""); + assert!(tooltip_shows(&mut h, egui::accesskit::Role::Label, "Font size", "Set font size"), "hovering the \"T\" icon shows \"Set font size\""); } /// A point inside glyph `i` of vertical type: `f` of the way down its advance, right of the @@ -2728,10 +2729,10 @@ fn type_mask_commits_the_glyphs_as_the_selection_in_one_step() { assert!(v.height() > 2 * v.width(), "{v:?}"); } -/// #1055: Escape cancels a Type Mask session whatever "Use Escape to Commit" says: the selection -/// and the layers stay as they were. +/// #1055: Cancel throws a Type Mask session away: the selection and the layers stay as they were. +/// (Escape commits it, as in the reference application: #12070, `mask_escape_tests`.) #[test] -fn type_mask_escape_leaves_the_selection_unchanged() { +fn type_mask_cancel_leaves_the_selection_unchanged() { let mut app = new_app(); app.run("select.all", json!({})).unwrap(); let (before, layers) = (selection_bounds(&app), app.session.active().unwrap().doc.layers.len()); @@ -2741,7 +2742,7 @@ fn type_mask_escape_leaves_the_selection_unchanged() { click(&mut h, p); assert!(h.state().ui.text_edit.as_ref().is_some_and(|ed| ed.mask), "typing a mask"); super::insert(h.state_mut(), "I"); - h.key_press(egui::Key::Escape); + super::cancel(h.state_mut()); h.run_steps(2); assert!(h.state().ui.text_edit.is_none()); assert_eq!(selection_bounds(h.state()), before); @@ -3005,19 +3006,18 @@ fn multi_click_without_a_session_does_nothing() { assert_eq!((ed.anchor, ed.caret), (5, 5)); } -/// #3036: ⇧ on the click that commits a Type Mask adds the glyphs to the selection and ⌥ -/// subtracts them, as in Photoshop; while typing, the working text has no Layers panel row. +/// #3036: while typing, the working text has no Layers panel row. ⇧ or ⌥ on the click that +/// commits a Type Mask no longer combine: the glyphs replace the selection (#12073, +/// `mask_replace_selection_tests`). #[test] -fn type_mask_shift_adds_and_alt_subtracts_without_a_layer_row() { +fn type_mask_shift_and_alt_replace_without_a_layer_row() { use crate::canvas::{ToolEvent, tool_event}; use crate::state::Tool; - use photocraft_geom::Rect; let mut app = new_app(); type_with(&mut app, Tool::HorizontalTypeMask, "I"); let glyphs = selection_bounds(&app).unwrap(); let mut app = new_app(); app.ui.extras.snap = false; // the second text would snap to the first one's selected edge - let rect = Rect::new(1000, 100, 1100, 200); app.run("select.rect", json!({"x": 1000, "y": 100, "width": 100, "height": 100})).unwrap(); // Type, then commit with a click outside the text holding `m`. let type_and_commit = |app: &mut PhotocraftApp, m: Modifiers| { @@ -3032,14 +3032,10 @@ fn type_mask_shift_adds_and_alt_subtracts_without_a_layer_row() { tool_event(app, ToolEvent::Up { x: 1500.0, y: 800.0 }, m); assert!(app.ui.text_edit.is_none()); }; - let at = |app: &PhotocraftApp, x: i32, y: i32| app.session.active().unwrap().doc.selection.as_ref().map_or(0.0, |s| s.sample_channel(x, y, 0)); - let stem = ((glyphs.x0 + glyphs.x1) / 2, (glyphs.y0 + glyphs.y1) / 2); type_and_commit(&mut app, Modifiers::SHIFT); - assert_eq!(selection_bounds(&app), Some(rect.union(&glyphs)), "⇧ adds"); - assert!(at(&app, stem.0, stem.1) > 0.99 && at(&app, 1050, 150) > 0.99); + assert_eq!(selection_bounds(&app), Some(glyphs), "⇧ replaces"); type_and_commit(&mut app, Modifiers::ALT); - assert!(at(&app, stem.0, stem.1) < 0.01, "⌥ subtracts the glyphs"); - assert!(at(&app, 1050, 150) > 0.99, "and keeps the rest"); + assert_eq!(selection_bounds(&app), Some(glyphs), "⌥ replaces"); } /// #7713: justification needs a paragraph box. On point text the Paragraph panel's four justify diff --git a/crates/ui-egui/src/tools/type_tool/ctrl_period_cancel_tests.rs b/crates/ui-egui/src/tools/type_tool/ctrl_period_cancel_tests.rs new file mode 100644 index 0000000000..73948ebf8c --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/ctrl_period_cancel_tests.rs @@ -0,0 +1,183 @@ +//! #12076: ⌘. (Ctrl+. off the Mac) ends a type editing session the way the options bar's Cancel +//! does, with any of the four type tools: the document, the selection and the history are as +//! before the session. ⇧⌘. stays Increase Type Size; outside a session, and while an input +//! method is composing (not measured), ⌘. does nothing. +//! Keys go through the app's shortcut handling, as on the canvas. + +use egui_kittest::Harness; +use photocraft_doc::{LayerContent, LayerId}; +use photocraft_raster::Surface; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +fn new_app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + // A selection away from the text, which a Type Mask session must leave as it is. + app.run("select.rect", json!({"x": 300, "y": 150, "width": 60, "height": 30})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + app +} + +/// Start new text with a click and type `s`, as the canvas does. +fn type_new(app: &mut PhotocraftApp, s: &str) { + super::pointer_up(app, [50.0, 100.0], [50.0, 100.0]); + super::insert(app, s); +} + +/// One frame of the app's shortcut handling for each of `events`. +fn send(app: PhotocraftApp, events: Vec) -> PhotocraftApp { + let mut h = Harness::builder().build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + // As `canvas_tests`' harness: the shortcuts wait for the app's fonts. + if ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + crate::shortcuts::handle(app, &ctx); + } + }, + app, + ); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + for event in events { + h.event(event); + h.run_steps(1); + } + h.into_state() +} + +fn key(key: egui::Key, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers } +} + +fn press(app: PhotocraftApp, k: egui::Key, modifiers: egui::Modifiers) -> PhotocraftApp { + send(app, vec![key(k, modifiers)]) +} + +fn command_period(app: PhotocraftApp) -> PhotocraftApp { + press(app, egui::Key::Period, egui::Modifiers::COMMAND) +} + +/// The selection (compared pixel for pixel, shown by its bounds), the history (oldest first) and +/// the layers' ids. +#[derive(PartialEq)] +struct Snapshot { + selection: Option, + history: Vec, + layers: Vec, +} + +impl std::fmt::Debug for Snapshot { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let bounds = self.selection.as_ref().map(Surface::content_bounds); + write!(f, "selection {bounds:?}, history {:?}, layers {:?}", self.history, self.layers) + } +} + +fn snapshot(app: &PhotocraftApp) -> Snapshot { + let st = app.session.active().unwrap(); + Snapshot { selection: st.doc.selection.clone(), history: st.history.entries(), layers: st.doc.layers.iter().map(|l| l.id).collect() } +} + +fn text_of(app: &PhotocraftApp, id: LayerId) -> String { + match &app.session.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Text(t) => t.text.clone(), + other => panic!("{}", other.kind_name()), + } +} + +fn size_of(app: &PhotocraftApp, id: LayerId) -> f32 { + match &app.session.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Text(t) => t.runs[0].style.size_pt, + other => panic!("{}", other.kind_name()), + } +} + +#[test] +fn command_period_cancels_new_text_with_every_type_tool() { + for tool in [Tool::Type, Tool::VerticalType, Tool::HorizontalTypeMask, Tool::VerticalTypeMask] { + let mut app = new_app(tool); + let before = snapshot(&app); + type_new(&mut app, "AB"); + assert!(app.ui.text_edit.is_some(), "{tool:?}: editing"); + let app = command_period(app); + assert!(app.ui.text_edit.is_none(), "{tool:?}: the session ends"); + assert_eq!(snapshot(&app), before, "{tool:?}: as before the session"); + } +} + +#[test] +fn command_period_restores_edited_text() { + for tool in [Tool::Type, Tool::VerticalType] { + let mut app = new_app(tool); + let orientation = if tool == Tool::VerticalType { "vertical" } else { "horizontal" }; + let made = app.run("type.create", json!({"text": "Hello", "x": 50, "y": 100, "orientation": orientation})).unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + let before = snapshot(&app); + super::edit_active(&mut app).unwrap(); + super::insert(&mut app, "CD"); + assert_ne!(text_of(&app, id), "Hello", "{tool:?}: typed"); + let app = command_period(app); + assert!(app.ui.text_edit.is_none(), "{tool:?}: the session ends"); + assert_eq!(text_of(&app, id), "Hello", "{tool:?}: the text is as before"); + assert_eq!(snapshot(&app), before, "{tool:?}: as before the session"); + } +} + +#[test] +fn shift_command_period_still_increases_the_type_size() { + let mut app = new_app(Tool::Type); + type_new(&mut app, "AB"); + let id = LayerId(app.ui.text_edit.as_ref().unwrap().layer); + let before = size_of(&app, id); + let app = press(app, egui::Key::Period, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT); + assert!(app.ui.text_edit.is_some(), "still editing"); + assert!(size_of(&app, id) > before, "Increase Type Size ran"); +} + +/// Not measured, kept as before: while an input method is composing, ⌘. leaves the session. +#[test] +fn command_period_while_an_input_method_composes_keeps_the_session() { + let mut app = new_app(Tool::Type); + type_new(&mut app, "AB"); + let preedit = egui::Event::Ime(egui::ImeEvent::Preedit { text: "にほ".into(), active_range_chars: None }); + let app = send(app, vec![preedit, key(egui::Key::Period, egui::Modifiers::COMMAND)]); + assert!(app.ui.text_edit.is_some(), "still editing"); +} + +#[test] +fn command_period_outside_a_type_session_changes_nothing() { + for tool in [Tool::Type, Tool::HorizontalTypeMask] { + let app = new_app(tool); + let before = snapshot(&app); + let app = command_period(app); + assert!(app.ui.text_edit.is_none(), "{tool:?}"); + assert_eq!(snapshot(&app), before, "{tool:?}"); + } +} + +/// Not measured, kept as before: once the composition text has gone but its committed text has +/// not arrived yet, ⌘. still leaves the session, as it does while composing. +#[test] +fn command_period_before_a_composition_commits_keeps_the_session() { + let mut app = new_app(Tool::Type); + type_new(&mut app, "AB"); + let preedit = |text: &str| egui::Event::Ime(egui::ImeEvent::Preedit { text: text.into(), active_range_chars: None }); + let app = send(app, vec![preedit("にほ"), preedit(""), key(egui::Key::Period, egui::Modifiers::COMMAND)]); + assert!(app.ui.text_edit.is_some(), "still editing"); +} + +#[test] +fn command_period_after_a_composition_commits_cancels() { + let mut app = new_app(Tool::Type); + let before = snapshot(&app); + type_new(&mut app, "AB"); + let preedit = egui::Event::Ime(egui::ImeEvent::Preedit { text: "にほ".into(), active_range_chars: None }); + let commit = egui::Event::Ime(egui::ImeEvent::Commit("日本".into())); + let app = send(app, vec![preedit, commit, key(egui::Key::Period, egui::Modifiers::COMMAND)]); + assert!(app.ui.text_edit.is_none(), "the session ends"); + assert_eq!(snapshot(&app), before, "as before the session"); +} diff --git a/crates/ui-egui/src/tools/type_tool/editing.rs b/crates/ui-egui/src/tools/type_tool/editing.rs index f93826c1d1..02ba991308 100644 --- a/crates/ui-egui/src/tools/type_tool/editing.rs +++ b/crates/ui-egui/src/tools/type_tool/editing.rs @@ -405,26 +405,26 @@ pub(crate) fn commit_shortcut(app: &mut PhotocraftApp, ctx: &egui::Context) -> b true } -/// [`commit`] with the modifiers held while committing: a Type Mask adds its glyphs to the -/// selection with ⇧, subtracts them with ⌥ and intersects with ⇧⌥ (Photoshop); with none it -/// replaces the selection. -pub fn commit_with(app: &mut PhotocraftApp, mods: egui::Modifiers) { +/// [`commit`] from a click, button or key that has modifiers held. They no longer change the +/// result, since a Type Mask always replaces the selection (#12073); the parameter stays so its +/// callers don't change. +pub fn commit_with(app: &mut PhotocraftApp, _mods: egui::Modifiers) { app.ui.type_insertion_style = None; crate::type_font_preview::clear(app); let current = app.session.active_index(); let Some(home) = app.ui.text_edit.as_ref().map(|ed| edit_home(app, ed)) else { - return commit_here(app, mods); + return commit_here(app); }; match home { Some(home) if Some(home) != current => { // An edit left in a background document commits there, in its own history (#6483). app.session.set_active(home); - commit_here(app, mods); + commit_here(app); if let Some(i) = current { app.session.set_active(i); } } - Some(_) => commit_here(app, mods), + Some(_) => commit_here(app), // Its document closed: there is nothing to commit into, and the layer id may name a // layer of another document. None => { @@ -445,7 +445,7 @@ pub(super) fn edit_home(app: &PhotocraftApp, ed: &TextEdit) -> Option { } /// [`commit_with`] in the active document, which is the edit's own. -fn commit_here(app: &mut PhotocraftApp, mods: egui::Modifiers) { +fn commit_here(app: &mut PhotocraftApp) { if app.ui.tool.is_type() { crate::type_transform::finish(app); } @@ -459,11 +459,11 @@ fn commit_here(app: &mut PhotocraftApp, mods: egui::Modifiers) { } let Some(text) = current_text(app, LayerId(ed.layer)) else { return }; if ed.mask { - // Type Mask: the text's glyphs become (or combine with) the selection and the working - // layer goes, all in the session's one history step. No text: nothing changes. - let operation = crate::tool_feedback::selection_mode(crate::state::Tool::HorizontalTypeMask, 0, mods); + // Type Mask: the text's glyphs replace the selection, with ⇧ or ⌥ held too, as in the + // reference application (#12073), and the working layer goes, all in the session's one + // history step. No text: nothing changes. if !text.trim().is_empty() - && let Err(e) = app.run("type.createSelection", json!({"layer": ed.layer, "removeLayer": true, "operation": operation, "coalesce": ed.session})) + && let Err(e) = app.run("type.createSelection", json!({"layer": ed.layer, "removeLayer": true, "operation": "new", "coalesce": ed.session})) { app.ui.status = e; app.ui.status_error = true; @@ -473,6 +473,34 @@ fn commit_here(app: &mut PhotocraftApp, mods: egui::Modifiers) { } return; } + // #12041: an Indexed Color or Bitmap document has no type layer to keep. The session's working + // layer is still edited and shown while typing, as the reference application shows it, and the + // commit makes what a Type Mask tool's commit makes: the glyphs become the selection and the + // layer goes, in the typing session's one history step - which keeps the "New Type Layer" name + // it was opened with, as Photoshop's state there is named. + // `photocraft_engine::type_cmds::commits_as_selection` holds the ticket's scope - the two modes + // and the measured horizontal point text - and why the check belongs to the commit and not to + // the `type.create` command. Three cases are not measured in these modes and keep today's + // behaviour: an edit of a layer the session did not create (`ed.created`), paragraph (box) and + // vertical text, whose editability a coverage mask could not give back, and a commit with no + // text in it, which is the empty-layer clean-up below. + let session_layer = LayerId(ed.layer); + let converts = app + .session + .active() + .is_some_and(|st| text_layer(&st.doc, session_layer).is_some_and(|t| photocraft_engine::type_cmds::commits_as_selection(st.doc.mode, t))); + let leaves_a_selection = ed.created && !text.trim().is_empty() && converts; + if leaves_a_selection { + if let Err(e) = app.run("type.createSelection", json!({"layer": ed.layer, "removeLayer": true, "operation": "new", "coalesce": ed.session})) { + // The refused step left the document alone: keep today's type layer, so what was typed + // is not lost with a selection that was never made. + app.ui.status = e; + app.ui.status_error = true; + return; + } + photocraft_engine::type_cmds::name_selection_commit(&mut app.session); + return; + } if text.trim().is_empty() && ed.created { let _ = app.run("layer.delete", json!({"layer": ed.layer})); } else if ed.created { @@ -526,3 +554,156 @@ fn undo_session(app: &mut PhotocraftApp, ed: &TextEdit) { let _ = app.run("edit.undo", json!({})); } } + +/// #12041: what the Type tool's commit does in a document whose colour mode has no type layers to +/// keep. The engine side - the mode check, the conversion it reuses and the step's name - is pinned +/// in `photocraft-engine`'s `cmd::type_indexed_mode_tests`; this is the tool's own commit, which is +/// where the difference is measured. +#[cfg(test)] +mod indexed_commit_tests { + use super::{cancel, commit, insert}; + use crate::PhotocraftApp; + use crate::state::Tool; + use crate::tools::type_tool::pointer_up; + use photocraft_doc::{ColorMode, LayerContent, LayerId, TextLayer}; + use serde_json::json; + + /// A new transparent document in `mode`: `rgb` keeps today's behaviour, `indexed` and `bitmap` + /// are the two the issue is about. + fn app(mode: &str) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 200, "background": "transparent"})).unwrap(); + match mode { + "indexed" => { + app.run("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + assert_eq!(doc_mode(&app), ColorMode::Indexed, "the document is Indexed Color"); + } + "bitmap" => { + app.run("image.mode.grayscale", json!({})).unwrap(); + app.run("image.mode.bitmap", json!({"method": "threshold", "frequency": 12, "shape": "diamond"})).unwrap(); + assert_eq!(doc_mode(&app), ColorMode::Bitmap, "the document is Bitmap"); + } + _ => assert_eq!(doc_mode(&app), ColorMode::Rgb, "the document is RGB"), + } + app.sync_views(); + app.ui.tool = Tool::Type; + app + } + + fn doc_mode(app: &PhotocraftApp) -> ColorMode { + app.session.active().unwrap().doc.mode + } + + fn text_of(app: &PhotocraftApp, id: LayerId) -> Option { + let doc = app.session.active().unwrap().doc.clone(); + super::text_layer(&doc, id).cloned() + } + + fn text_layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).count() + } + + fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.walk().len() + } + + fn states(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() + } + + fn last_state(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().history.entries().last().cloned() + } + + fn selection(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds()) + } + + /// The reference application, in an Indexed Color and in a Bitmap document: clicking and typing + /// works and the text is shown while editing, and the commit leaves no type layer but a + /// selection in the shape of the glyphs, as the one history state named "New Type Layer". + #[test] + fn committing_in_indexed_color_or_bitmap_leaves_the_glyphs_selected() { + // The bounds the same text covers where it does become a layer. + let mut rgb = app("rgb"); + pointer_up(&mut rgb, [80.0, 120.0], [80.0, 120.0]); + insert(&mut rgb, "Hi"); + commit(&mut rgb); + let glyphs = rgb.session.active().unwrap().doc.layers.last().unwrap().surface().unwrap().content_bounds(); + assert_eq!(text_layers(&rgb), 1, "an RGB document keeps its type layer"); + assert!(selection(&rgb).is_none(), "and selects nothing"); + assert_eq!(last_state(&rgb).as_deref(), Some("New Type Layer"), "as the session's one state"); + + for mode in ["indexed", "bitmap"] { + let mut app = app(mode); + let (layers_before, states_before) = (layers(&app), states(&app)); + + // Typing: the working layer is there, and shown, as measured. + pointer_up(&mut app, [80.0, 120.0], [80.0, 120.0]); + insert(&mut app, "Hi"); + assert!(app.ui.text_edit.is_some(), "{mode}: the session is open"); + assert_eq!(text_layers(&app), 1, "{mode}: the text is edited on a layer"); + + commit(&mut app); + assert!(app.ui.text_edit.is_none(), "{mode}: the commit ends the session"); + assert_eq!(text_layers(&app), 0, "{mode}: committing leaves no type layer"); + assert_eq!(layers(&app), layers_before, "{mode}: the working layer went with it"); + assert_eq!(selection(&app), Some(glyphs), "{mode}: the typed glyphs are the selection"); + assert_eq!(states(&app), states_before + 1, "{mode}: one state for the session"); + assert_eq!(last_state(&app).as_deref(), Some("New Type Layer"), "{mode}: and its name"); + + app.run("edit.undo", json!({})).unwrap(); + assert!(selection(&app).is_none(), "{mode}: one undo takes the selection"); + assert_eq!(layers(&app), layers_before, "{mode}: and the whole session"); + } + } + + /// Cancelling such a session is unchanged: no layer and no selection are left, as elsewhere. + #[test] + fn cancelling_in_indexed_color_or_bitmap_leaves_nothing() { + for mode in ["rgb", "indexed", "bitmap"] { + let mut app = app(mode); + let (layers_before, states_before) = (layers(&app), states(&app)); + pointer_up(&mut app, [80.0, 120.0], [80.0, 120.0]); + insert(&mut app, "Hi"); + cancel(&mut app); + assert!(app.ui.text_edit.is_none(), "{mode}: the session ended"); + assert_eq!(text_layers(&app), 0, "{mode}: no layer is left"); + assert_eq!(layers(&app), layers_before, "{mode}: no layer is added"); + assert!(selection(&app).is_none(), "{mode}: nothing is selected"); + assert_eq!(states(&app), states_before, "{mode}: and no history state"); + } + } + + /// #12041 measures the horizontal point text you click and type. Paragraph (box) text and + /// vertical type are on its *Not measured* list, whose rule is that they keep today's + /// behaviour - and today's behaviour is the right one here anyway: a coverage mask cannot bring + /// back a box that reflows or a column that runs down the page, so their editable layer stays. + #[test] + fn paragraph_and_vertical_text_keep_their_type_layer_in_indexed_and_bitmap() { + use photocraft_doc::text::{Orientation, TextShape}; + + for mode in ["indexed", "bitmap"] { + // A dragged paragraph box. + let mut boxed = app(mode); + pointer_up(&mut boxed, [40.0, 60.0], [320.0, 180.0]); + insert(&mut boxed, "Hi"); + let box_layer = LayerId(boxed.ui.text_edit.as_ref().unwrap().layer); + assert!(matches!(text_of(&boxed, box_layer).map(|t| t.shape), Some(TextShape::Box { .. })), "{mode}: the setup made paragraph text"); + commit(&mut boxed); + assert_eq!(text_layers(&boxed), 1, "{mode}: paragraph text keeps its editable layer"); + assert!(selection(&boxed).is_none(), "{mode}: and is not turned into a selection"); + + // Vertical point text. + let mut column_app = app(mode); + column_app.ui.tool = Tool::VerticalType; + pointer_up(&mut column_app, [80.0, 120.0], [80.0, 120.0]); + insert(&mut column_app, "Hi"); + let column = LayerId(column_app.ui.text_edit.as_ref().unwrap().layer); + assert!(text_of(&column_app, column).is_some_and(|t| t.orientation == Orientation::Vertical), "{mode}: the setup made vertical text"); + commit(&mut column_app); + assert_eq!(text_layers(&column_app), 1, "{mode}: vertical text keeps its editable layer"); + assert!(selection(&column_app).is_none(), "{mode}: and is not turned into a selection"); + } + } +} diff --git a/crates/ui-egui/src/tools/type_tool/fonts.rs b/crates/ui-egui/src/tools/type_tool/fonts.rs index 7c8162e3f4..022b978f8b 100644 --- a/crates/ui-egui/src/tools/type_tool/fonts.rs +++ b/crates/ui-egui/src/tools/type_tool/fonts.rs @@ -338,6 +338,18 @@ pub(super) fn font_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui, current: & Some(style) } +/// The options bar's hover text on the [`font_picker`] just drawn in `ui`: its name field and its +/// arrow, by the ids [`family_picker_in`] gives them. Only the options bar calls it (#12057); the +/// panels sharing the picker keep their texts. +pub(super) fn font_picker_tip(ui: &egui::Ui, tip: &str) { + let field = ui.make_persistent_id(egui::IdSalt::new("type-font")); + for id in [field, field.with("arrow")] { + if let Some(r) = ui.ctx().read_response(id) { + r.on_hover_text(tip); + } + } +} + /// The font list's maximum height: it scrolls inside the menu, under the fixed preview and filters. pub(super) const FONT_LIST_HEIGHT: f32 = 440.0; /// The font list's width: star, style expander, name, format badge and sample. diff --git a/crates/ui-egui/src/tools/type_tool/keys.rs b/crates/ui-egui/src/tools/type_tool/keys.rs index 74c81c2f7d..3d3067f29b 100644 --- a/crates/ui-egui/src/tools/type_tool/keys.rs +++ b/crates/ui-egui/src/tools/type_tool/keys.rs @@ -255,7 +255,11 @@ fn handle_pressed_key( insert(app, "\t"); } Key::Escape if crate::type_transform::active(app) => crate::type_transform::cancel_drag(app), - Key::Escape if edit.edit.mask => cancel(app), + // A Type Mask commits on Escape as on ⌘↩, whatever "Use ESC to commit" says; the options bar's + // Cancel still throws it away (#12070). Escape on an empty mask text, or while an input + // method is composing, was not measured and still cancels. + Key::Escape if edit.edit.mask && (edit.text.is_empty() || edit.edit.preedit.is_some()) => cancel(app), + Key::Escape if edit.edit.mask => commit(app), Key::Escape if app.session.prefs().type_.use_esc_to_commit => commit(app), Key::Escape => cancel(app), Key::A if modifiers.command => { @@ -268,6 +272,20 @@ fn handle_pressed_key( Key::T if modifiers.command && !modifiers.shift && !modifiers.alt => { let _ = crate::menus::invoke(app, ctx, "window.panel.character", json!({})); } + // ⌘. throws the session away as the options bar's Cancel does (#12076); ⇧⌘. stays + // Increase Type Size. Mid-composition (until its text commits or its reset completes) or + // mid ⌘-drag it was not measured and goes on to the ⌘ fallback below, as before. + Key::Period + if modifiers.command + && !modifiers.shift + && !modifiers.alt + && edit.edit.preedit.is_none() + && app.type_ime.incoming.is_none() + && !reset_guarded(app, ctx.viewport_id()) + && !crate::type_transform::active(app) => + { + cancel(app) + } _ if modifiers.command => { if key == Key::Z { crate::type_transform::cancel_drag(app); diff --git a/crates/ui-egui/src/tools/type_tool/locked_layer_alert_tests.rs b/crates/ui-egui/src/tools/type_tool/locked_layer_alert_tests.rs new file mode 100644 index 0000000000..3d0bc20228 --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/locked_layer_alert_tests.rs @@ -0,0 +1,102 @@ +//! #12040: a Type tool click on a text layer under Lock All, its own or an enclosing group's, +//! makes the layer active and shows the reference application's alert instead of starting an edit +//! the engine would refuse at the first keystroke. A position lock alone, and a click on empty +//! canvas, keep today's behaviour. + +use super::*; +use crate::state::DialogKind; + +const MESSAGE: &str = "Could not use the type tool because the layer is locked."; +/// A point on the glyphs of the text layer `locked_text` makes. +const ON_TEXT: (f64, f64) = (60.0, 95.0); +/// A point on the canvas well away from any text. +const OFF_TEXT: (f64, f64) = (300.0, 40.0); + +/// A committed type layer reading "Locked text" at `ON_TEXT`, and an empty layer above it that +/// is active, so the click's activation shows. +fn locked_text(lock: serde_json::Value) -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.sync_views(); + app.ui.tool = crate::state::Tool::Type; + pointer_up(&mut app, [50.0, 100.0], [50.0, 100.0]); + insert(&mut app, "Locked text"); + commit(&mut app); + let id = active_layer(&app).unwrap(); + app.run("layer.lockLayers", lock).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + assert_ne!(active_layer(&app), Some(id)); + assert_eq!(hit_layer(&mut app, ON_TEXT.0, ON_TEXT.1), Some(id), "the click lands on the text"); + (app, id) +} + +fn active_layer(app: &PhotocraftApp) -> Option { + app.session.active().and_then(|st| st.active_layer) +} + +fn history_len(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn error_dialogs(app: &PhotocraftApp) -> Vec { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(String::from)).collect() +} + +fn click(app: &mut PhotocraftApp, (x, y): (f64, f64)) -> bool { + pointer_down(app, x, y, egui::Modifiers::NONE) +} + +#[test] +fn a_click_on_a_text_layer_under_lock_all_alerts_instead_of_editing() { + let (mut app, id) = locked_text(json!({"all": true})); + let steps = history_len(&app); + assert!(click(&mut app, ON_TEXT), "the click is the Type tool's"); + assert_eq!(active_layer(&app), Some(id), "the clicked layer becomes active"); + assert_eq!(error_dialogs(&app), [MESSAGE]); + assert!(app.ui.text_edit.is_none(), "no edit starts"); + assert_eq!(history_len(&app), steps, "no history state"); + // OK closes the alert and changes nothing else (an alert's OK, and ↩, take the cancel path). + let dialog = app.ui.dialogs[0].id; + crate::dialogs::cancel(&mut app, dialog).unwrap(); + assert!(app.ui.dialogs.is_empty()); + assert!(app.ui.text_edit.is_none()); + assert_eq!(history_len(&app), steps); + assert_eq!(current_text(&app, id).as_deref(), Some("Locked text")); +} + +#[test] +fn lock_all_on_an_enclosing_group_alerts_too() { + // No lock of the layer's own (`{}` would toggle Lock All on it). + let (mut app, id) = locked_text(json!({"position": false})); + app.run("layer.select", json!({"layer": id.0, "mode": "replace"})).unwrap(); + app.run("layer.groupLayers", json!({})).unwrap(); + // The new group is active; lock it, then make another layer active. + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let steps = history_len(&app); + assert!(click(&mut app, ON_TEXT)); + assert_eq!(active_layer(&app), Some(id)); + assert_eq!(error_dialogs(&app), [MESSAGE]); + assert!(app.ui.text_edit.is_none()); + assert_eq!(history_len(&app), steps); +} + +#[test] +fn a_position_lock_alone_still_edits() { + let (mut app, id) = locked_text(json!({"position": true})); + assert!(click(&mut app, ON_TEXT)); + assert!(error_dialogs(&app).is_empty()); + assert_eq!(app.ui.text_edit.as_ref().map(|e| e.layer), Some(id.0), "the click edits the text"); +} + +#[test] +fn a_click_on_empty_canvas_with_a_locked_text_layer_active_starts_new_text() { + let (mut app, id) = locked_text(json!({"all": true})); + app.run("layer.select", json!({"layer": id.0, "mode": "replace"})).unwrap(); + assert!(!click(&mut app, OFF_TEXT), "no text there: the press is left to start new text"); + pointer_up(&mut app, [OFF_TEXT.0, OFF_TEXT.1], [OFF_TEXT.0, OFF_TEXT.1]); + assert!(error_dialogs(&app).is_empty()); + let edit = app.ui.text_edit.as_ref().expect("new text is being edited"); + assert!(edit.created); + assert_ne!(edit.layer, id.0, "a new type layer"); +} diff --git a/crates/ui-egui/src/tools/type_tool/mask_escape_tests.rs b/crates/ui-egui/src/tools/type_tool/mask_escape_tests.rs new file mode 100644 index 0000000000..30566900b0 --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/mask_escape_tests.rs @@ -0,0 +1,152 @@ +//! #12070: Escape commits a Type Mask session the way ⌘↩ does, whatever "Use Escape to Commit" +//! says: the text outline becomes the selection in one history state and no layer is added. An +//! empty mask text and a composing input method still cancel, and the Type tool's Escape still +//! follows the preference. (A ⌘ transform drag's Escape arm stays first; masks have no transform +//! box yet, #12082.) Keys go through the app's shortcut handling, as on the canvas. + +use egui_kittest::Harness; +use photocraft_doc::LayerId; +use photocraft_raster::Surface; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +fn new_app(tool: Tool, use_esc_to_commit: bool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.run("prefs.set", json!({"path": "type.useEscToCommit", "value": use_esc_to_commit})).unwrap(); + // Away from the text, so New, Add, Subtract and Intersect each leave a different selection. + app.run("select.rect", json!({"x": 300, "y": 150, "width": 60, "height": 30})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + app +} + +/// Start new text with a click and type `s`, as the canvas does. +fn type_new(app: &mut PhotocraftApp, s: &str) -> LayerId { + super::pointer_up(app, [50.0, 100.0], [50.0, 100.0]); + super::insert(app, s); + LayerId(app.ui.text_edit.as_ref().unwrap().layer) +} + +/// One frame of the app's shortcut handling for each of `events`. +fn send(app: PhotocraftApp, events: Vec) -> PhotocraftApp { + let mut h = Harness::builder().build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + // As `canvas_tests`' harness: the shortcuts wait for the app's fonts. + if ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + crate::shortcuts::handle(app, &ctx); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + for event in events { + h.event(event); + h.run_steps(1); + } + h.into_state() +} + +fn key(key: egui::Key, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers } +} + +fn escape(app: PhotocraftApp) -> PhotocraftApp { + send(app, vec![key(egui::Key::Escape, egui::Modifiers::NONE)]) +} + +/// The selection (compared pixel for pixel, shown by its bounds), the history (oldest first) and +/// the layer count. +#[derive(PartialEq)] +struct Snapshot { + selection: Option, + history: Vec, + layers: usize, +} + +impl std::fmt::Debug for Snapshot { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let bounds = self.selection.as_ref().map(Surface::content_bounds); + write!(f, "selection {bounds:?}, history {:?}, {} layers", self.history, self.layers) + } +} + +fn snapshot(app: &PhotocraftApp) -> Snapshot { + let st = app.session.active().unwrap(); + Snapshot { selection: st.doc.selection.clone(), history: st.history.entries(), layers: st.doc.layers.len() } +} + +#[test] +fn escape_commits_a_type_mask_as_command_return_does() { + for tool in [Tool::HorizontalTypeMask, Tool::VerticalTypeMask] { + for use_esc_to_commit in [true, false] { + let what = format!("{tool:?}, useEscToCommit={use_esc_to_commit}"); + let session = || { + let mut app = new_app(tool, use_esc_to_commit); + let before = snapshot(&app); + type_new(&mut app, "AB"); + (app, before) + }; + let (app, before) = session(); + let escaped = escape(app); + let (app, _) = session(); + let returned = send(app, vec![key(egui::Key::Enter, egui::Modifiers::COMMAND)]); + assert!(escaped.ui.text_edit.is_none(), "{what}: the session ends"); + let after = snapshot(&escaped); + let bounds = after.selection.as_ref().map(Surface::content_bounds); + assert!(bounds.is_some_and(|r| r.x1 < 300), "{what}: the text outline alone is the selection: {bounds:?}"); + assert_eq!(after.history.len(), before.history.len() + 1, "{what}: one history state"); + assert_eq!(after.layers, before.layers, "{what}: no layer is added"); + assert_eq!(after, snapshot(&returned), "{what}: the same as ⌘↩"); + } + } +} + +#[test] +fn escape_with_an_empty_mask_text_changes_nothing() { + for tool in [Tool::HorizontalTypeMask, Tool::VerticalTypeMask] { + for use_esc_to_commit in [true, false] { + let what = format!("{tool:?}, useEscToCommit={use_esc_to_commit}"); + let mut app = new_app(tool, use_esc_to_commit); + let before = snapshot(&app); + type_new(&mut app, ""); + let app = escape(app); + assert!(app.ui.text_edit.is_none(), "{what}"); + assert_eq!(snapshot(&app), before, "{what}"); + } + } +} + +#[test] +fn escape_while_an_input_method_composes_still_cancels_a_type_mask() { + let preedit = || egui::Event::Ime(egui::ImeEvent::Preedit { text: "にほ".into(), active_range_chars: None }); + let session = || { + let mut app = new_app(Tool::HorizontalTypeMask, true); + let before = snapshot(&app); + type_new(&mut app, "AB"); + (app, before) + }; + let (app, _) = session(); + let app = send(app, vec![preedit()]); + assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.preedit.is_some()), "composing"); + let (app, before) = session(); + let app = send(app, vec![preedit(), key(egui::Key::Escape, egui::Modifiers::NONE)]); + assert!(app.ui.text_edit.is_none()); + assert_eq!(snapshot(&app), before); +} + +#[test] +fn the_type_tools_escape_still_follows_the_preference() { + for (use_esc_to_commit, kept) in [(true, true), (false, false)] { + let mut app = new_app(Tool::Type, use_esc_to_commit); + let id = type_new(&mut app, "AB"); + let app = escape(app); + assert!(app.ui.text_edit.is_none()); + let layer = app.session.active().unwrap().doc.layer(id).is_some(); + assert_eq!(layer, kept, "useEscToCommit={use_esc_to_commit}: committed, or cancelled and the new layer gone"); + } +} diff --git a/crates/ui-egui/src/tools/type_tool/mask_replace_selection_tests.rs b/crates/ui-egui/src/tools/type_tool/mask_replace_selection_tests.rs new file mode 100644 index 0000000000..dba036ae85 --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/mask_replace_selection_tests.rs @@ -0,0 +1,135 @@ +//! #12073: committing a Type Mask always replaces the selection with the text outline, with ⇧, +//! ⌥ or ⇧⌥ held too: a click outside the text, the Commit button and ⌘↩ all go through +//! `commit_with`. `type.createSelection` keeps its `operation` param for scripts. + +use egui::Modifiers; +use egui_kittest::Harness; +use photocraft_raster::Surface; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const COMBOS: [Modifiers; 4] = [Modifiers::NONE, Modifiers::SHIFT, Modifiers::ALT, Modifiers { shift: true, alt: true, ..Modifiers::NONE }]; + +/// A document with a selection away from the text, so Add, Subtract and Intersect would each +/// leave something other than the text outline. +fn new_app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 400})).unwrap(); + app.run("select.rect", json!({"x": 600, "y": 250, "width": 100, "height": 100})).unwrap(); + app.sync_views(); + app.ui.extras.snap = false; + app.ui.tool_options.type_size = 48.0; + app.ui.tool = Tool::HorizontalTypeMask; + app +} + +fn click(app: &mut PhotocraftApp, x: f64, y: f64, mods: Modifiers) { + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x, y }, mods); +} + +/// Start a mask with a click at `at` and type `s`. +fn mask(app: &mut PhotocraftApp, at: (f64, f64), s: &str) { + mask_with(app, at, s, Modifiers::NONE); +} + +/// [`mask`] started by a click holding `mods`. +fn mask_with(app: &mut PhotocraftApp, at: (f64, f64), s: &str, mods: Modifiers) { + click(app, at.0, at.1, mods); + assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask), "typing a mask"); + super::insert(app, s); +} + +fn selection(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().doc.selection.clone() +} + +fn bounds(s: &Option) -> Option { + s.as_ref().map(Surface::content_bounds) +} + +/// The selection a plain commit of `s` at `at` leaves: the text outline alone. +fn outline(at: (f64, f64), s: &str) -> Option { + let mut app = new_app(); + mask(&mut app, at, s); + super::commit_with(&mut app, Modifiers::NONE); + let outline = selection(&app); + assert!(bounds(&outline).is_some_and(|r| r.x1 < 600), "the text alone: {:?}", bounds(&outline)); + outline +} + +#[test] +fn every_commit_replaces_the_selection_whatever_modifiers_are_held() { + let outline = outline((100.0, 200.0), "AB"); + for mods in COMBOS { + let mut app = new_app(); + mask(&mut app, (100.0, 200.0), "AB"); + super::commit_with(&mut app, mods); + assert!(app.ui.text_edit.is_none(), "{mods:?}"); + assert!(selection(&app) == outline, "{mods:?}: {:?}, not the outline {:?}", bounds(&selection(&app)), bounds(&outline)); + } +} + +#[test] +fn a_modified_click_outside_the_text_replaces_the_selection() { + let outline = outline((100.0, 200.0), "AB"); + for mods in COMBOS { + let mut app = new_app(); + mask(&mut app, (100.0, 200.0), "AB"); + click(&mut app, 450.0, 60.0, mods); + assert!(app.ui.text_edit.is_none(), "{mods:?}: the click commits"); + assert!(selection(&app) == outline, "{mods:?}: {:?}", bounds(&selection(&app))); + } +} + +#[test] +fn shift_command_return_replaces_the_selection() { + let outline = outline((100.0, 200.0), "AB"); + let mut app = new_app(); + mask(&mut app, (100.0, 200.0), "AB"); + let mut h = Harness::builder().build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + // As `canvas_tests`' harness: the shortcuts wait for the app's fonts. + if ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + crate::shortcuts::handle(app, &ctx); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h.event(egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND | Modifiers::SHIFT }); + h.run_steps(1); + let app = h.into_state(); + assert!(app.ui.text_edit.is_none()); + assert!(selection(&app) == outline, "{:?}", bounds(&selection(&app))); +} + +/// The reference application's "AB", then ⇧-clicks to commit it and to start "C", then "C" +/// committed: only "C" is selected. (Here a click outside the text commits without starting new +/// text, so that is two ⇧-clicks.) +#[test] +fn the_next_mask_after_a_shift_click_commit_replaces_the_first() { + let second = outline((300.0, 200.0), "C"); + let mut app = new_app(); + mask(&mut app, (100.0, 200.0), "AB"); + click(&mut app, 450.0, 60.0, Modifiers::SHIFT); + assert!(app.ui.text_edit.is_none(), "the ⇧-click commits"); + mask_with(&mut app, (300.0, 200.0), "C", Modifiers::SHIFT); + click(&mut app, 450.0, 60.0, Modifiers::SHIFT); + assert!(selection(&app) == second, "{:?}, not only \"C\" {:?}", bounds(&selection(&app)), bounds(&second)); +} + +#[test] +fn type_create_selection_still_combines_for_scripts() { + let mut app = new_app(); + let rect = bounds(&selection(&app)).unwrap(); + app.run("type.createSelection", json!({"text": "AB", "x": 100, "y": 200, "size": 48, "operation": "add"})).unwrap(); + let added = bounds(&selection(&app)).unwrap(); + assert_eq!(added.union(&rect), added, "the rectangle is kept"); + assert!(added.x0 < rect.x0, "and the text is added"); +} diff --git a/crates/ui-egui/src/tools/type_tool/options_bar.rs b/crates/ui-egui/src/tools/type_tool/options_bar.rs index 33287d1234..20176a4133 100644 --- a/crates/ui-egui/src/tools/type_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/type_tool/options_bar.rs @@ -1,6 +1,6 @@ use super::defaults::{apply, formatting_params, open_color_picker, shown_scale, target, target_doc, type_unit}; use super::editing::{cancel, commit_with}; -use super::fonts::{font_picker, fonts_ready, selected_style, style_label, styles}; +use super::fonts::{font_picker, font_picker_tip, fonts_ready, selected_style, style_label, styles}; use super::keys::is_vertical; use super::{Color32, LayerId, PhotocraftApp, Stroke, byte_of, insertion_style, json, selected_styles, text_layer}; @@ -43,6 +43,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { None => apply(app, ui.ctx(), json!({"font": fam})), } } + font_picker_tip(ui, tl!("Search and select fonts")); let style_family = if fam.is_empty() { styles_at(app).map(|(c, _)| c.font_family).unwrap_or_default() } else { fam.clone() }; let opts: Vec<(String, String)> = styles(&style_family).into_iter().map(|s| (s.clone(), style_label(&s))).collect(); let opts_ref: Vec<(String, &str)> = opts.iter().map(|(a, b)| (a.clone(), b.as_str())).collect(); @@ -50,15 +51,19 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.tool_options.type_style = style.clone(); apply(app, ui.ctx(), json!({"fontStyle": style})); } + // The menu's button, by the id its combo box takes from "type-style"; "Style" stays its name. + if let Some(menu) = ui.ctx().read_response(ui.make_persistent_id(egui::IdSalt::new("type-style"))) { + menu.on_hover_text(tl!("Set font style")); + } } let (r, icon) = ui.allocate_exact_size(egui::vec2(18.0, 22.0), egui::Sense::hover()); crate::icons::paint(ui, r, "type", 13.0, t.icon); icon.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, tl!("Font size"))); // Photoshop's "T" scrubs the size field beside it, like the Character panel's icons (#6437). - crate::widgets::scrub_option_icon(ui, &icon, tl!("Font size")); + crate::widgets::scrub_option_icon(ui, &icon, tl!("Set font size")); let (unit, label) = type_unit(app); let mut display = size * unit; - if crate::widgets::value_field(ui, &mut display, unit..=1296.0 * unit, label, 66.0).changed() { + if crate::widgets::value_field(ui, &mut display, unit..=1296.0 * unit, label, 66.0).on_hover_text(tl!("Set font size")).changed() { let size = display / unit; app.ui.tool_options.type_size = size; apply(app, ui.ctx(), json!({"size": size, "metricsAsShown": true})); @@ -95,9 +100,24 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }, None => o.type_align.as_str(), }; - for (align, icon, tip) in + // Vertical text shows Top / Center / Bottom for the same left / center / right values, after the + // targeted layer's orientation, or with no text targeted the Vertical Type tool's (#12059). The + // Type Mask tools keep the horizontal buttons (not measured). + let vertical = !app.ui.tool.is_type_mask() + && match super::defaults::target_text(app) { + Some(t) => t.orientation == photocraft_doc::text::Orientation::Vertical, + None => app.ui.tool == crate::state::Tool::VerticalType, + }; + let buttons = if vertical { + [ + ("left", "vertical-align-top", tl!("Top align text")), + ("center", "vertical-align-middle", tl!("Center text")), + ("right", "vertical-align-bottom", tl!("Bottom align text")), + ] + } else { [("left", "align-left", tl!("Left align text")), ("center", "align-center", tl!("Center text")), ("right", "align-right", tl!("Right align text"))] - { + }; + for (align, icon, tip) in buttons { if crate::icons::button(ui, icon, 24.0, shown_align == align, tip).clicked() { app.ui.tool_options.type_align = align.into(); apply(app, ui.ctx(), json!({"align": align})); @@ -128,7 +148,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; ui.painter().rect_filled(rect, 2.0, Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]))); ui.painter().rect_stroke(rect, 2.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Outside); - let resp = resp.on_hover_text(tl!("Set the text color")); + let resp = resp.on_hover_text(tl!("Set text color")); resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Set the text color"))); if resp.clicked() { open_color_picker(app, [c[0], c[1], c[2]]); @@ -264,20 +284,14 @@ pub(super) fn kerning_field(ui: &mut egui::Ui, shown: &str, width: f32) -> Optio } let presets = ["Metrics", "Optical", "0", "-100", "-75", "-50", "-25", "-10", "-5", "5", "10", "25", "50", "75", "100", "200"]; let (press, close) = crate::press_menu::PressCombo::before(ui, "props-kern-presets"); - let combo = craft_ui::ComboBox::from_id_salt("props-kern-presets") - .selected_text("") - .width(16.0) - .height(420.0) - .icon(crate::widgets::chevron_icon) - .close_behavior(close) - .show_ui(ui, |ui| { - for p in presets { - let item = ui.selectable_label(p == shown, p); - if press.chosen(ui, &item) { - out = parse_kerning(p); - } + let combo = crate::widgets::combo_list(ui, "props-kern-presets", "", 16.0, close, |ui| { + for p in presets { + let item = ui.selectable_label(p == shown, p); + if press.chosen(ui, &item) { + out = parse_kerning(p); } - }); + } + }); press.after(&combo.response); let _ = combo.response.accessible_name(tl!("Kerning")); }); diff --git a/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs b/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs new file mode 100644 index 0000000000..a41a0e2f2c --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/options_tooltips_tests.rs @@ -0,0 +1,121 @@ +//! #12057: the Type options bar's font family menu, font style menu, font size icon and field, +//! and text colour swatch carry the reference application's tooltips (also their accessible +//! descriptions). The controls keep their names, and the Character panel's font menu, which +//! shares the family picker, keeps its text. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; + +const FAMILY_TIP: &str = "Search and select fonts"; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("type.create", json!({"text": "Sample", "font": "Inter", "size": 18})).unwrap(); + app +} + +/// `draw` in a row, once the app's fonts are set up (the first pass has none). +fn harness(draw: fn(&mut PhotocraftApp, &mut egui::Ui)) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1400.0, 600.0)).build_ui_state( + move |ui, app| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + ui.horizontal(|ui| draw(app, ui)); + } + }, + app(), + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + super::options_bar::options_bar(app, ui); +} + +fn character_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + ui.vertical(|ui| super::panel::character_panel(app, ui, false)); +} + +fn description(n: egui_kittest::Node<'_>) -> Option { + n.accesskit_node().description().map(|d| d.to_string()) +} + +fn described_by_label(h: &Harness<'static, PhotocraftApp>, label: &str) -> Vec { + h.query_all_by_label(label).filter_map(description).collect() +} + +fn described_by_role(h: &Harness<'static, PhotocraftApp>, role: Role) -> Vec { + h.query_all_by_role(role).filter_map(description).collect() +} + +/// Every text shape drawn this frame, tooltips included. +fn drawn(h: &Harness<'static, PhotocraftApp>) -> Vec { + fn collect(shape: &egui::Shape, text: &mut Vec) { + match shape { + egui::Shape::Text(shape) => text.push(shape.galley.job.text.clone()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, text)), + _ => {} + } + } + let mut text = Vec::new(); + for shape in &h.output().shapes { + collect(&shape.shape, &mut text); + } + text +} + +#[test] +fn the_font_family_menu_has_the_reference_tooltip() { + let h = harness(options_bar); + // The name field (the bar's only text input) and its arrow, which keeps the name "Font". + assert_eq!(described_by_role(&h, Role::TextInput), [FAMILY_TIP]); + assert_eq!(described_by_label(&h, "Font"), [FAMILY_TIP]); +} + +#[test] +fn the_font_style_menu_has_the_reference_tooltip_and_keeps_its_name() { + let h = harness(options_bar); + assert_eq!(described_by_label(&h, "Style"), ["Set font style"]); +} + +#[test] +fn the_font_size_field_has_the_reference_tooltip() { + let h = harness(options_bar); + // The bar's only number field. + assert_eq!(described_by_role(&h, Role::SpinButton), ["Set font size"]); +} + +#[test] +fn the_font_size_icon_shows_the_reference_tooltip_and_keeps_its_name() { + let mut h = harness(options_bar); + // The icon itself: the size field beside it is labelled by it, so it is named "Font size" too. + h.get_by_role_and_label(Role::Label, "Font size").hover(); + h.run_steps(8); + let text = drawn(&h); + assert!(text.iter().any(|t| t == "Set font size"), "{text:?}"); + assert!(!text.iter().any(|t| t == "Font size"), "old tooltip: {text:?}"); +} + +#[test] +fn the_text_color_swatch_has_the_reference_tooltip_and_keeps_its_name() { + let h = harness(options_bar); + let found = described_by_label(&h, "Set the text color"); + assert_eq!(found, ["Set text color"]); +} + +/// A guard, so it passes without the fix too: it fails if the tooltip moves into the picker that +/// the panels share. +#[test] +fn the_character_panel_font_menu_keeps_its_text() { + let h = harness(character_panel); + assert!(h.query_by_label("Font").is_some(), "the panel draws its font menu"); + let found: Vec = described_by_label(&h, "Font").into_iter().chain(described_by_role(&h, Role::TextInput)).collect(); + assert!(!found.iter().any(|d| d == FAMILY_TIP), "{found:?}"); +} diff --git a/crates/ui-egui/src/tools/type_tool/pointer.rs b/crates/ui-egui/src/tools/type_tool/pointer.rs index 19bab778a4..53b924a2a2 100644 --- a/crates/ui-egui/src/tools/type_tool/pointer.rs +++ b/crates/ui-egui/src/tools/type_tool/pointer.rs @@ -140,7 +140,7 @@ pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifie } return true; } - // ⇧/⌥ on that click combine a Type Mask with the selection. + // A Type Mask replaces the selection with ⇧ or ⌥ on that click too (#12073). commit_with(app, mods); return true; // Photoshop: a click outside commits without starting new text } @@ -152,6 +152,13 @@ pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifie } if let Some(id) = hit_layer(app, x, y) { let _ = app.session.select_layer(id); + // Lock All (the layer's own or a group's) refuses the edit before it starts, as the engine + // would refuse the first keystroke; the reference application says so in an alert (#12040). + if app.session.active().is_some_and(|st| st.doc.effective_locks(id).all) { + let message = json!({"message": tl!("Could not use the type tool because the layer is locked.")}); + app.ui.open_dialog(crate::state::DialogKind::Error, message.as_object().cloned().unwrap_or_default()); + return true; + } let key = session_key(app); if begin_edit(app, id, &key).is_err() { return true; diff --git a/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs b/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs new file mode 100644 index 0000000000..9d3145e9ef --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs @@ -0,0 +1,178 @@ +//! #12059: for vertical text the options bar's alignment buttons are Top / Center / Bottom, after +//! the targeted text layer's orientation, or with no text targeted the Vertical Type tool's. They +//! still set left / center / right, and the lit one follows the targeted paragraph. The Type Mask +//! tools keep the horizontal buttons (not measured). + +use egui::accesskit::{Role, Toggled}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LayerId, text::TextAlign}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +const HORIZONTAL: [&str; 3] = ["Left align text", "Center text", "Right align text"]; +const VERTICAL: [&str; 3] = ["Top align text", "Center text", "Bottom align text"]; + +fn new_app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 400})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + app +} + +/// A text layer with `orientation`, made the active layer (selected, not edited). +fn text_layer(app: &mut PhotocraftApp, orientation: &str) -> LayerId { + let made = app.run("type.create", json!({"text": "AB CD", "x": 400, "y": 100, "orientation": orientation})).unwrap(); + LayerId(made["layer"].as_u64().unwrap()) +} + +fn bar(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 60.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + ui.horizontal(|ui| super::options_bar(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(3); + h +} + +/// Which of the two button sets the bar shows; panics on a mix or neither. +fn shown(h: &Harness<'static, PhotocraftApp>) -> [&'static str; 3] { + let has = |label: &str| h.query_by_role_and_label(Role::Button, label).is_some(); + match (has("Top align text") && has("Bottom align text"), has("Left align text") && has("Right align text")) { + (true, false) => VERTICAL, + (false, true) => HORIZONTAL, + (true, true) => panic!("both the vertical and the horizontal buttons"), + (false, false) => panic!("no alignment buttons"), + } +} + +fn lit(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { + h.get_by_role_and_label(Role::Button, label).accesskit_node().toggled() == Some(Toggled::True) +} + +fn align_of(app: &PhotocraftApp, id: LayerId) -> TextAlign { + match &app.session.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Text(t) => t.paragraphs[0].style.align, + other => panic!("{}", other.kind_name()), + } +} + +#[test] +fn with_no_text_targeted_the_tool_decides() { + for (tool, buttons) in [(Tool::VerticalType, VERTICAL), (Tool::Type, HORIZONTAL)] { + let h = bar(new_app(tool)); + assert_eq!(shown(&h), buttons, "{tool:?}"); + assert!(lit(&h, buttons[0]), "{tool:?}: the default, left, lights the first button"); + } +} + +#[test] +fn a_selected_text_layer_decides_whatever_the_tool() { + for tool in [Tool::Type, Tool::VerticalType] { + for (orientation, buttons) in [("vertical", VERTICAL), ("horizontal", HORIZONTAL)] { + let mut app = new_app(tool); + text_layer(&mut app, orientation); + assert_eq!(shown(&bar(app)), buttons, "{tool:?}, {orientation} layer selected"); + } + } +} + +#[test] +fn text_being_edited_decides() { + for (orientation, buttons) in [("vertical", VERTICAL), ("horizontal", HORIZONTAL)] { + let mut app = new_app(Tool::Type); + text_layer(&mut app, orientation); + super::edit_active(&mut app).unwrap(); + assert!(app.ui.text_edit.is_some()); + assert_eq!(shown(&bar(app)), buttons, "editing {orientation} text"); + } +} + +#[test] +fn the_vertical_buttons_set_left_center_and_right_and_follow_the_paragraph() { + for (label, align, value) in + [("Bottom align text", TextAlign::Right, "right"), ("Center text", TextAlign::Center, "center"), ("Top align text", TextAlign::Left, "left")] + { + let mut app = new_app(Tool::VerticalType); + let id = text_layer(&mut app, "vertical"); + let mut h = bar(app); + h.get_by_role_and_label(Role::Button, label).click(); + h.run_steps(2); + assert_eq!(align_of(h.state(), id), align, "{label}"); + assert_eq!(h.state().ui.tool_options.type_align, value, "{label}: the tool default too"); + for other in VERTICAL { + assert_eq!(lit(&h, other), other == label, "{label} clicked: {other}"); + } + } +} + +#[test] +fn the_type_mask_tools_keep_the_horizontal_buttons() { + for tool in [Tool::VerticalTypeMask, Tool::HorizontalTypeMask] { + assert_eq!(shown(&bar(new_app(tool))), HORIZONTAL, "{tool:?}, idle"); + let mut app = new_app(tool); + super::pointer_up(&mut app, [400.0, 100.0], [400.0, 100.0]); + assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask), "{tool:?}: typing a mask"); + assert_eq!(shown(&bar(app)), HORIZONTAL, "{tool:?}, editing"); + } +} + +/// Clicking Toggle text orientation switches the buttons in the same frame (the toggle is drawn +/// before them). +#[test] +fn toggling_the_orientation_switches_the_buttons() { + let mut app = new_app(Tool::Type); + text_layer(&mut app, "horizontal"); + let mut h = bar(app); + assert_eq!(shown(&h), HORIZONTAL); + h.get_by_role_and_label(Role::Button, "Toggle text orientation").click(); + h.run_steps(1); + assert_eq!(shown(&h), VERTICAL, "now vertical"); +} + +/// A text edit left in a background document decides by its own layer, not by a same-id layer of +/// the active document (layer ids repeat across documents; as `styles_at`, #9179). +#[test] +fn a_background_text_edit_decides_by_its_own_document() { + let mut app = new_app(Tool::Type); + let a = app.session.active().unwrap().doc.id.0; + let id = text_layer(&mut app, "vertical"); + app.ui.text_edit = Some(crate::state::TextEdit { + layer: id.0, + document: Some(a), + caret: 0, + anchor: 0, + session: "s".into(), + created: false, + mask: false, + dragging: false, + resize: None, + preedit: None, + }); + // The same file opened twice, its copy of the layer turned horizontal. + let twin = app.session.active().unwrap().doc.as_ref().clone(); + app.session.open_document(twin, None); + app.run("type.orientation.horizontal", json!({"layer": id.0})).unwrap(); + assert_ne!(app.session.active().unwrap().doc.id.0, a, "the other document is active"); + assert_eq!(shown(&bar(app)), VERTICAL, "the edited layer is vertical"); +} + +/// The lit button follows the targeted paragraph, not the tool default. +#[test] +fn the_lit_button_follows_the_paragraph_not_the_tool_default() { + let mut app = new_app(Tool::VerticalType); + app.ui.tool_options.type_align = "center".into(); + let made = app.run("type.create", json!({"text": "AB CD", "x": 400, "y": 100, "orientation": "vertical", "align": "right"})).unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + assert_eq!(align_of(&app, id), TextAlign::Right); + let h = bar(app); + for label in VERTICAL { + assert_eq!(lit(&h, label), label == "Bottom align text", "{label}"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index bbd674c4f4..e8fe67f8bd 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -56,7 +56,8 @@ pub(crate) use pen::over_first_anchor; use pen::pen_to_json; pub(crate) use pen::{PATH_OPS, pen_path, pen_replace}; pub use pen::{ - cancel_stale, closes_path_at, freeform_finish, pen_break_handle, pen_commit, pen_down, pen_end, pen_grab_handle, pen_move, pen_undo_last_point, pen_up, + cancel_stale, closes_path_at, continues_path_at, freeform_finish, pen_break_handle, pen_commit, pen_down, pen_end, pen_grab_handle, pen_move, + pen_undo_last_point, pen_up, }; #[cfg(test)] use pen::{closing, pen_path_op}; diff --git a/crates/ui-egui/src/tools/vector_ui/pen.rs b/crates/ui-egui/src/tools/vector_ui/pen.rs index 563b78455b..d31dac59a8 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen.rs @@ -1,6 +1,6 @@ use super::curvature::{curvature_hit, curvature_refresh}; use super::options::selected_shape; -use super::path_ops::{active_shape_path, targeted_vector_mask, work_path_shown}; +use super::path_ops::{targeted_vector_mask, targeted_vector_mask_id, work_path_shown}; use super::shapes::{fill_param, stroke_param}; use super::{Document, LayerContent, Path, PenPath, PhotocraftApp, Resumed, Tokens, Tool, ToolOptions, Value, json, vec2}; @@ -34,6 +34,12 @@ pub fn closes_path_at(app: &PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { } } +/// Would a Pen click at `(x, y)` carry on an open path from its endpoint there (#6593)? The canvas +/// shows the continue-path pointer there (#9356), as the endpoints look like any anchor. +pub fn continues_path_at(app: &PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { + tool == Tool::Pen && app.ui.pen.as_ref().is_none_or(|p| p.knots.is_empty()) && resume_at(app, x, y, 6.0 / app.point_zoom().max(0.01) as f64).is_some() +} + /// Pen press: close on the first anchor, reshape the last anchor's outgoing handle, /// or add a new anchor (dragging a new anchor pulls symmetrical handles). With ⇧ a new anchor /// lands on the nearest 45° ray from the previous one, at the pointer's projection onto it. @@ -47,10 +53,12 @@ pub fn pen_down(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { } // A press on an endpoint of an open path carries on drawing it, as in Photoshop (#6593): the // press then acts on its last anchor, so a drag pulls out the next segment's handle. + let mut resuming = false; if app.ui.pen.as_ref().is_none_or(|p| p.knots.is_empty()) && let Some(resumed) = resume_at(app, x, y, tol) { app.ui.pen = Some(resumed); + resuming = true; } let Some(owner) = capture_pen_owner(app) else { return }; let pen = app.ui.pen.get_or_insert_with(PenPath::default); @@ -61,7 +69,10 @@ pub fn pen_down(app: &mut PhotocraftApp, x: f64, y: f64, shift: bool) { pen.adjusting_in = false; pen.last_pointer = Some([x, y]); pen.reposition = false; + // The press that carries a path on never closes it, even when its other end is in reach too: + // the canvas showed the continue-path pointer there (`continues_path_at`). if let Some(first) = pen.knots.first().map(|k| k[0]) + && !resuming && on_closing_anchor(pen, x, y, tol) { // Pressing the first anchor closes the path on release. Until then a stand-in for it @@ -512,21 +523,24 @@ fn doc_path<'a>(doc: &'a Document, name: &str) -> Option<&'a Path> { /// The path a Pen path carries on (#6593): a targeted vector mask, else in Shape mode the /// selected shape layer's, else the path a new Pen path would join (the one selected in the Paths /// panel, else the work path). Its Paths-panel name ("layer" for a layer's), layer and path. -fn resume_target(app: &PhotocraftApp) -> Option<(String, Option, Path)> { +fn resume_target(app: &PhotocraftApp) -> Option<(String, Option, &Path)> { let st = app.session.active()?; - if let Some((id, p)) = targeted_vector_mask(app) { - return Some(("layer".to_string(), Some(id), p)); + // Borrowed, not cloned: the canvas asks on every hover (`continues_path_at`). + if let Some(id) = targeted_vector_mask_id(app) { + let mask = st.doc.layer(photocraft_doc::LayerId(id))?.vector_mask.as_ref()?; + return Some(("layer".to_string(), Some(id), &mask.path)); } if app.ui.tool_options.vector_mode == "shape" { - let (id, p) = active_shape_path(app)?; - return Some(("layer".to_string(), Some(id), p)); + let l = st.active_layer.and_then(|id| st.doc.layer(id))?; + let LayerContent::Shape(sh) = &l.content else { return None }; + return Some(("layer".to_string(), Some(l.id.0), &sh.path)); } let name = app.ui.selected_path.clone().filter(|n| path_exists(&st.doc, n)).unwrap_or_else(|| "work".into()); // A Work Path hidden by Make Selection isn't carried on: a new path replaces it (#6079). if name == "work" && !work_path_shown(app) { return None; } - let p = doc_path(&st.doc, &name)?.clone(); + let p = doc_path(&st.doc, &name)?; Some((name, None, p)) } @@ -550,17 +564,15 @@ fn resumed(doc: u64, name: String, layer: Option, index: usize, sub: &photo pub(super) fn resume_at(app: &PhotocraftApp, x: f64, y: f64, tol: f64) -> Option { let doc = app.session.active()?.doc.id.0; let (name, layer, path) = resume_target(app)?; - let near = |k: &photocraft_doc::Knot| (k.anchor.x - x).hypot(k.anchor.y - y) < tol; - path.subpaths.iter().enumerate().filter(|(_, s)| !s.closed).find_map(|(i, s)| { - let reversed = if s.knots.last().is_some_and(near) { - false - } else if s.knots.first().is_some_and(near) { - true - } else { - return None; - }; - Some(resumed(doc, name.clone(), layer, i, s, reversed)) - }) + let dist = |k: &photocraft_doc::Knot| (k.anchor.x - x).hypot(k.anchor.y - y); + // With several ends in reach (a short path, or ends of two subpaths close together, zoomed + // out) the nearest one is carried on; on a tie the last anchor, then the earlier subpath. + let ends = + path.subpaths.iter().enumerate().filter(|(_, s)| !s.closed).flat_map(|(i, s)| { + [(s.knots.last(), false), (s.knots.first(), true)].into_iter().filter_map(move |(k, reversed)| Some((i, s, reversed, dist(k?)))) + }); + let (i, s, reversed, _) = ends.filter(|e| e.3 < tol).reduce(|best, e| if e.3 < best.3 { e } else { best })?; + Some(resumed(doc, name, layer, i, s, reversed)) } /// The endpoint Direct Selection has selected ([`crate::direct_select::selected_open_end`]), as diff --git a/crates/ui-egui/src/transform_type_tests.rs b/crates/ui-egui/src/transform_type_tests.rs index e179e4f6d5..b6bcfc2198 100644 --- a/crates/ui-egui/src/transform_type_tests.rs +++ b/crates/ui-egui/src/transform_type_tests.rs @@ -58,6 +58,7 @@ fn type_layers_offer_free_transform_but_not_distort_or_perspective() { crop: None, sampler: None, sampler_at: None, + color: None, }; assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.freeTransform")); assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.distort")); diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index c69a3ec099..ee4489e4a6 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -11,6 +11,12 @@ pub(crate) struct Runtime { /// The startup prompt and the self-update behind it (desktop). #[cfg(not(target_arch = "wasm32"))] updater: craft_update::updater::Updater, + /// What the last self-update came to, shown in the result window until it is closed. + #[cfg(not(target_arch = "wasm32"))] + last_update: craft_update::updater::Status, + /// The check running was asked for with Help ▸ Check for Updates. + #[cfg(not(target_arch = "wasm32"))] + requested: bool, } impl Default for Runtime { @@ -20,6 +26,10 @@ impl Default for Runtime { notified_version: None, #[cfg(not(target_arch = "wasm32"))] updater: craft_update::updater::Updater::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION), + #[cfg(not(target_arch = "wasm32"))] + last_update: craft_update::updater::Status::Idle, + #[cfg(not(target_arch = "wasm32"))] + requested: false, } } } @@ -51,11 +61,33 @@ pub(crate) fn check(app: &mut PhotocraftApp, _ctx: &egui::Context, params: Value app.updates_rt.startup_checked = true; // A release the user dismissed is offered again by a manual check. app.updates_rt.notified_version = None; + // The window shows this check from now on. + #[cfg(not(target_arch = "wasm32"))] + { + app.updates_rt.requested = true; + app.updates_rt.updater.dismiss_status(); + app.updates_rt.last_update = craft_update::updater::Status::Idle; + // A check made before the first frame leaves the last self-update's records for the + // next start. + app.services.last_update = None; + } } result } pub(crate) fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(read) = app.services.last_update.take() { + use craft_update::updater::Status as Shown; + app.updates_rt.last_update = match read() { + Some(Ok(version)) => Shown::Updated(version), + Some(Err(reason)) => Shown::InstallFailed(reason), + None => Shown::Idle, + }; + if app.updates_rt.last_update != Shown::Idle { + app.ui.updates_open = true; + } + } // `updates.status` also polls (automation may consume the result before this frame). app.session.updates.poll(); if let Status::Available { release } = &app.session.updates.status @@ -64,7 +96,19 @@ pub(crate) fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { app.updates_rt.notified_version = Some(release.version.clone()); app.ui.updates_open = true; #[cfg(not(target_arch = "wasm32"))] - app.updates_rt.updater.offer(release_of(release)); + { + let updater = &mut app.updates_rt.updater; + updater.offer(release_of(release)); + // While an update installs or waits for the app to close, or while the launcher keeps + // this version, no prompt opens: a manual check reports that state in the result window. + if std::mem::take(&mut app.updates_rt.requested) && !updater.prompt_open() { + updater.check_now(ctx); + } + } + } + #[cfg(not(target_arch = "wasm32"))] + if !matches!(app.session.updates.status, Status::Checking) { + app.updates_rt.requested = false; } if app.session.updates.check.is_none() { return; @@ -89,7 +133,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { { let was_open = app.updates_rt.updater.prompt_open(); app.updates_rt.updater.tick(ctx); - // The restart helper is scheduled before the app closes, so no update starts over unsaved work. + // An update starts, and a ready one asks the app to close, only while no work is unsaved. let clean = !app.has_unsaved_work(); match app.updates_rt.updater.show_if(ctx, clean) { craft_update::updater::Action::None => {} @@ -98,8 +142,9 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { // relaunches once the process exits. craft_update::updater::Action::Close => ctx.send_viewport_cmd(egui::ViewportCommand::Close), } + // The last self-update's outcome, hidden while the prompt showed, is still shown after it. if was_open && !app.updates_rt.updater.prompt_open() { - app.ui.updates_open = false; + app.ui.updates_open = app.updates_rt.last_update != craft_update::updater::Status::Idle; } } if let Some(url) = download { @@ -108,15 +153,37 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { if app.updates_rt.updater.prompt_open() { return; } - if app.ui.updates_open { - let dialog = craft_update::CheckResultDialog::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION); - match dialog.show(ctx, &check_status(&app.session.updates.status)) { - craft_update::CheckResultResponse::None => {} - craft_update::CheckResultResponse::Close => app.ui.updates_open = false, - craft_update::CheckResultResponse::CheckAgain => { - let _ = check(app, ctx, serde_json::json!({})); - } + let status = shown_status(app); + let dialog = craft_update::CheckResultDialog::new(&crate::UPDATE_APP, photocraft_engine::build_info::VERSION); + match dialog.show(ctx, &status) { + craft_update::CheckResultResponse::None => {} + craft_update::CheckResultResponse::Close => { + app.ui.updates_open = false; + app.updates_rt.updater.dismiss_status(); + app.updates_rt.last_update = craft_update::updater::Status::Idle; } + craft_update::CheckResultResponse::CheckAgain => { + let _ = check(app, ctx, serde_json::json!({})); + } + craft_update::CheckResultResponse::RestartToUpdate => app.updates_rt.updater.restart_to_update(), + } +} + +/// What the open result window shows: the updater's answer to a manual check (an update installing +/// or ready, or a version the launcher keeps), else the last self-update's outcome, else the +/// engine's check. +#[cfg(not(target_arch = "wasm32"))] +fn shown_status(app: &PhotocraftApp) -> craft_update::updater::Status { + use craft_update::updater::Status as Shown; + let updater = app.updates_rt.updater.status(); + if !app.ui.updates_open { + Shown::Idle + } else if *updater != Shown::Idle { + updater.clone() + } else if app.updates_rt.last_update != Shown::Idle { + app.updates_rt.last_update.clone() + } else { + check_status(&app.session.updates.status) } } @@ -270,6 +337,59 @@ mod tests { assert!(app.updates_rt.updater.prompt_open()); } + #[cfg(not(target_arch = "wasm32"))] + fn press_escape(app: &mut PhotocraftApp, ctx: &egui::Context) { + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let mut output = ctx.run_ui(egui::RawInput { events: vec![escape], ..Default::default() }, |ui| show(app, ui.ctx())); + output.textures_delta.clear(); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn the_last_update_opens_the_result_window_once_until_it_is_closed() { + use craft_update::updater::Status as Shown; + let (mut app, _, _) = app(); + app.services.last_update = Some(|| Some(Ok("99.0.0".into()))); + let ctx = egui::Context::default(); + at(&mut app, &ctx, 0.0); + assert!(app.ui.updates_open); + assert_eq!(shown_status(&app), Shown::Updated("99.0.0".into())); + assert!(app.services.last_update.is_none(), "read once"); + at(&mut app, &ctx, 1.0); + assert_eq!(shown_status(&app), Shown::Updated("99.0.0".into()), "shown until closed"); + press_escape(&mut app, &ctx); + assert!(!app.ui.updates_open); + assert_eq!(app.updates_rt.last_update, Shown::Idle); + assert_eq!(shown_status(&app), Shown::Idle); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_failed_update_is_reported_until_a_manual_check_replaces_it() { + use craft_update::updater::Status as Shown; + let (mut app, calls, _) = app(); + app.services.last_update = Some(|| Some(Err("the installer exited with code 1603".into()))); + app.session.edit_prefs(|p| p.general.automatically_check_updates = false); + let ctx = egui::Context::default(); + at(&mut app, &ctx, 0.0); + assert_eq!(shown_status(&app), Shown::InstallFailed("the installer exited with code 1603".into())); + menus::invoke(&mut app, &ctx, "help.checkForUpdates", serde_json::json!({})).unwrap(); + assert_eq!(*calls.lock().unwrap(), 1); + assert_eq!(shown_status(&app), Shown::Checking, "the window shows the new check"); + + let (mut early, _, _) = self::app(); + early.services.last_update = Some(|| Some(Err("unread".into()))); + menus::invoke(&mut early, &ctx, "help.checkForUpdates", serde_json::json!({})).unwrap(); + at(&mut early, &ctx, 0.0); + assert_eq!(shown_status(&early), Shown::Checking, "a check before the first frame is not replaced by the last update"); + assert!(early.services.last_update.is_none()); + + let (mut quiet, _, _) = self::app(); + quiet.services.last_update = Some(|| None); + at(&mut quiet, &ctx, 0.0); + assert!(!quiet.ui.updates_open, "nothing to report opens nothing"); + } + #[test] fn a_manual_check_that_fails_to_start_opens_the_status_window() { let mut app = diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 3b4320dd0d..1fb94c9d72 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -44,19 +44,21 @@ pub use color::{ #[cfg(test)] use color::{checker_tile_id, checker_uv}; pub use dropdown::{ - dropdown, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_hovered, dropdown_with_tooltips, menu_scroll, swatch_popup, + combo_list, dropdown, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_hovered, dropdown_with_tooltips, menu_scroll, swatch_popup, }; pub(crate) use fields::compact_wrapping_value_field; #[cfg(test)] use fields::{FieldOpts, NUMERIC_INPUT_LIMIT, value_field_in}; pub use fields::{ - POPUP_ARROW_W, PopupFieldResponse, VALUE_FIELD_H, compact_value_field, elided_label, elided_label_sensed, popup_value_field, value_field, value_field_named, + POPUP_ARROW_W, PopupFieldResponse, VALUE_FIELD_H, compact_value_field, elided_label, elided_label_sensed, popup_value_field, value_field, + value_field_named, value_field_whole_alerting, }; pub(crate) use panel::body_margin; pub use panel::{ FOOTER_BAR, chevron_icon, drop_line, footer_height, hairline, panel_footer, panel_menu_button, pill_tab, section_label, style_spectrum_popup_menu, surface, vline, }; +pub(crate) use scrub::scrub_label_within; pub use scrub::{scrub_label, scrub_option_icon, scrub_option_label}; #[cfg(test)] use slider::DOUBLE_CLICK_S; diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index b862d89a74..05c0c46735 100644 --- a/crates/ui-egui/src/widgets/dropdown.rs +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -1,7 +1,7 @@ use super::panel::chevron_icon; use super::scrub::take_label_scrub_name; use super::slider::wheel_notches_of; -use super::{Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, Vec2, pos2, type_ahead, vec2}; +use super::{Align2, Pos2, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, Vec2, pos2, type_ahead, vec2}; /// A compact labelled dropdown in the studio style. pub fn dropdown(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool { @@ -79,57 +79,56 @@ fn dropdown_with( // The list opens on the press: press, drag onto an option and release to choose it (#2735). let (press, close) = crate::press_menu::PressCombo::before(ui, id); let texts: Vec = options.iter().map(|(_, l)| shown(l)).collect(); - let response = - craft_ui::ComboBox::from_id_salt(id).selected_text(label).width(width).height(420.0).icon(chevron_icon).close_behavior(close).show_ui(ui, |ui| { - fit_widest_option(ui, texts.iter().map(|l| l.as_str())); - // A typed letter jumps to the next option starting with it, ↩ closes the list (#1481). - let labels: Vec<&str> = texts.iter().map(|l| l.as_str()).collect(); - let shown = options.iter().position(|(v, _)| v == current); - if let Some((v, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + let response = combo_list(ui, id, label, width, close, |ui| { + fit_widest_option(ui, texts.iter().map(|l| l.as_str())); + // A typed letter jumps to the next option starting with it, ↩ closes the list (#1481). + let labels: Vec<&str> = texts.iter().map(|l| l.as_str()).collect(); + let shown = options.iter().position(|(v, _)| v == current); + if let Some((v, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + *current = v.clone(); + chosen.push(v.clone()); + reveal = true; + keyed = true; + } + // Over the open list the wheel steps the value too, instead of scrolling the list. + over_list = wheel && ui.rect_contains_pointer(ui.clip_rect()); + if over_list { + let stepped = wheel_steps(ui, wheel_id, true, current, options); + wheeled = !stepped.is_empty(); + reveal |= wheeled; + chosen.extend(stepped); + } + // The row nearest the pointer, by its distance to each row. + let pointer = ui.ctx().pointer_hover_pos().filter(|_| ui.rect_contains_pointer(ui.clip_rect())); + let mut nearest: Option<(f32, &T)> = None; + for (i, ((v, _), text)) in options.iter().zip(texts.iter()).enumerate() { + if i > 0 && starts_group(v) { + list_separator(ui); + } + let item = ui.selectable_label(v == current, text.as_str()); + if reveal && v == current { + item.scroll_to_me(None); + } + if item.hovered() { + hovered = Some(v.clone()); + } + if let Some(p) = pointer { + let d = (item.rect.top() - p.y).max(p.y - item.rect.bottom()).max(0.0); + if nearest.is_none_or(|(n, _)| d < n) { + nearest = Some((d, v)); + } + } + if press.chosen(ui, &item) { *current = v.clone(); chosen.push(v.clone()); - reveal = true; - keyed = true; } - // Over the open list the wheel steps the value too, instead of scrolling the list. - over_list = wheel && ui.rect_contains_pointer(ui.clip_rect()); - if over_list { - let stepped = wheel_steps(ui, wheel_id, true, current, options); - wheeled = !stepped.is_empty(); - reveal |= wheeled; - chosen.extend(stepped); - } - // The row nearest the pointer, by its distance to each row. - let pointer = ui.ctx().pointer_hover_pos().filter(|_| ui.rect_contains_pointer(ui.clip_rect())); - let mut nearest: Option<(f32, &T)> = None; - for (i, ((v, _), text)) in options.iter().zip(texts.iter()).enumerate() { - if i > 0 && starts_group(v) { - list_separator(ui); - } - let item = ui.selectable_label(v == current, text.as_str()); - if reveal && v == current { - item.scroll_to_me(None); - } - if item.hovered() { - hovered = Some(v.clone()); - } - if let Some(p) = pointer { - let d = (item.rect.top() - p.y).max(p.y - item.rect.bottom()).max(0.0); - if nearest.is_none_or(|(n, _)| d < n) { - nearest = Some((d, v)); - } - } - if press.chosen(ui, &item) { - *current = v.clone(); - chosen.push(v.clone()); - } - } - // Between two rows (item spacing) the pointer hovers neither; it is still over the list, - // so keep previewing the nearest row instead of flashing the current value back (#2553). - if hovered.is_none() { - hovered = nearest.map(|(_, v)| v.clone()); - } - }); + } + // Between two rows (item spacing) the pointer hovers neither; it is still over the list, + // so keep previewing the nearest row instead of flashing the current value back (#2553). + if hovered.is_none() { + hovered = nearest.map(|(_, v)| v.clone()); + } + }); // A scrubby caption drawn just before the dropdown names it; otherwise its own name does. let response = match take_label_scrub_name(ui, response.response.rect) { Some(label) => response.response.labelled_by(label), @@ -304,6 +303,124 @@ pub fn menu_scroll(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R out.inner } +/// A dropdown: a button showing `selected_text` (at least `width` wide, wider for a longer text) +/// whose list (`add_contents`) opens below it on a click. The list is as tall as its options up to +/// the room the window has on that side, scrolling only past that (#5495): Photoshop's dropdowns +/// open at full height. egui's `ComboBox` capped every list at the size its popup takes on the +/// frame it opens (`default_area_size`, 400 pt), so the Layers panel's 27 blend modes scrolled. +/// +/// The list never covers its button, as in Photoshop: it opens below the button, or above it when +/// the whole list doesn't fit below and there is more room above, and scrolls when it doesn't fit +/// on that side either. Over the button, the release of the click that opened it would choose the +/// row under the pointer. Its left edge is the button's and its side only depends on its rows' +/// height, so it stays put while its value (and with it the button's width) changes, as the wheel +/// steps it over the open list (#1747). The ids are `craft_ui::ComboBox`'s (egui's), so +/// `ComboBox::is_open` and [`crate::press_menu::PressCombo`] apply. +pub fn combo_list( + ui: &mut Ui, + id_salt: impl egui::AsIdSalt, + selected_text: impl Into, + width: f32, + close: egui::PopupCloseBehavior, + add_contents: impl FnOnce(&mut Ui) -> R, +) -> egui::InnerResponse> { + let button_id = ui.make_persistent_id(egui::IdSalt::new(id_salt)); + let popup_id = button_id.with("popup"); + let selected_text = selected_text.into(); + ui.horizontal(|ui| { + let ctx = ui.ctx().clone(); + let button = combo_button(ui, button_id, &selected_text, width, egui::Popup::is_id_open(&ctx, popup_id)); + let enabled = ui.is_enabled(); + button.widget_info(|| { + let mut info = egui::WidgetInfo::new(egui::Role::ComboBox); + info.enabled = enabled; + info.current_text_value = Some(selected_text.text().to_owned()); + info + }); + // The room below and above the button, less the popup frame's margin and stroke. The + // rows' full height is measured on the (invisible) pass that sizes the list as it opens. + let visible = crate::work_area::visible_rect(&ctx).shrink(MENU_EDGE); + let frame = ui.spacing().menu_margin.sum().y + 2.0; + let below = visible.bottom() - button.rect.bottom() - frame; + let above = button.rect.top() - visible.top() - frame; + let rows_id = popup_id.with("rows"); + let rows = ctx.data(|d| d.get_temp::(rows_id)); + let up = rows.is_some_and(|rows| rows > below) && above > below; + // Only the room that side has, even when it is small: a taller list would be pushed back + // into the window, over its button (#5495 review). + let room = (if up { above } else { below }).max(0.0); + // Above the button the list's top is placed from its known height: egui would place its + // bottom by the size the list had last frame, so it would move as it settles, under a + // click aimed at a row. `chrome` is the popup frame's margin and stroke. + let anchor = match rows.filter(|_| up) { + Some(rows) => { + let chrome = egui::Frame::popup(&ctx.global_style()).total_margin().sum().y; + let top = button.rect.top() - rows.min(room) - chrome; + egui::Rect::from_x_y_ranges(button.rect.x_range(), top - button.rect.height()..=top) + } + None => button.rect, + }; + let parent_layer = ui.layer_id(); + let inner = egui::Popup::menu(&button) + .id(popup_id) + .anchor(anchor) + .align(egui::RectAlign::BOTTOM_START) + .align_alternatives(&[]) + .width(button.rect.width()) + .close_behavior(close) + .style(egui::style::StyleModifier::default()) + .show(|ui| { + crate::press_menu::above_parent_ui(parent_layer, ui); + ui.set_min_width(ui.available_width()); + // A popup's Ui is only as tall as the popup was last frame (400 pt on the first), + // so ask for the whole room: the area still shrinks to its rows when they need less. + let scroll = egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, |ui| { + // Options don't wrap in a list as narrow as its button: they widen it. + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + add_contents(ui) + }); + let rows = scroll.content_size.y; + ui.ctx().data_mut(|d| d.insert_temp(rows_id, rows)); + scroll.inner + }) + .map(|r| r.inner); + egui::InnerResponse::new(inner, button) + }) + .inner +} + +/// The button of a [`combo_list`], drawn as egui's `ComboBox` draws its own. +fn combo_button(ui: &mut Ui, id: egui::Id, text: &egui::WidgetText, width: f32, open: bool) -> Response { + let background = ui.painter().add(egui::Shape::Noop); + let margin = ui.spacing().button_padding; + let min_height = ui.spacing().interact_size.y; + let mut outer = ui.available_rect_before_wrap(); + outer.set_height(outer.height().max(min_height)); + let mut content = ui.new_child(egui::UiBuilder::new().max_rect(outer.shrink2(margin))); + let icon_spacing = content.spacing().icon_spacing; + let icon_size = Vec2::splat(content.spacing().icon_width); + let wrap_mode = content.wrap_mode(); + let wrap_width = if wrap_mode == egui::TextWrapMode::Extend { f32::INFINITY } else { content.available_width() - icon_spacing - icon_size.x }; + let galley = text.clone().into_galley(&content, Some(wrap_mode), wrap_width, egui::TextStyle::Button); + let size = vec2((galley.size().x + icon_spacing + icon_size.x).max(width - 2.0 * margin.x), galley.size().y.max(icon_size.y)); + let (_, rect) = content.allocate_space(size); + let mut outer = content.min_rect().expand2(margin); + outer.set_height(outer.height().max(min_height)); + let response = ui.interact(outer, id, Sense::click()); + if ui.is_rect_visible(outer) { + let visuals = if open { &ui.visuals().widgets.open } else { ui.style().interact(&response) }; + let shape = + egui::epaint::RectShape::new(outer.expand(visuals.expansion), visuals.corner_radius, visuals.weak_bg_fill, visuals.bg_stroke, StrokeKind::Inside); + ui.painter().set(background, shape); + let icon_rect = Align2::RIGHT_CENTER.align_size_within_rect(icon_size, rect); + chevron_icon(ui, icon_rect.expand(visuals.expansion), visuals, open); + let text_rect = Align2::LEFT_CENTER.align_size_within_rect(galley.size(), rect); + ui.painter().galley(text_rect.min, galley, visuals.text_color()); + } + ui.advance_cursor_after_rect(outer); + response +} + /// One scroll arrow of an overflowing menu: hovering scrolls that way, as in Photoshop's and the /// system menus. It doesn't page on a click: egui closes a context menu on any click inside it, /// so the page would never be seen. `width` is the rows' width. Returns the scroll step for the @@ -375,23 +492,22 @@ pub fn dropdown_with_tooltips(ui: &mut Ui, id: &str, name: let label = options.iter().find(|(v, _, _)| v == current).map(|(_, l, _)| tl!(l)).unwrap_or("—"); let mut changed = false; let (press, close) = crate::press_menu::PressCombo::before(ui, id); - let response = - craft_ui::ComboBox::from_id_salt(id).selected_text(label).width(width).height(420.0).icon(chevron_icon).close_behavior(close).show_ui(ui, |ui| { - fit_widest_option(ui, options.iter().map(|(_, l, _)| tl!(l))); - let labels: Vec<&str> = options.iter().map(|(_, l, _)| tl!(l)).collect(); - let shown = options.iter().position(|(v, _, _)| v == current); - if let Some((v, _, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + let response = combo_list(ui, id, label, width, close, |ui| { + fit_widest_option(ui, options.iter().map(|(_, l, _)| tl!(l))); + let labels: Vec<&str> = options.iter().map(|(_, l, _)| tl!(l)).collect(); + let shown = options.iter().position(|(v, _, _)| v == current); + if let Some((v, _, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) { + *current = v.clone(); + changed = true; + } + for (v, l, tip) in options { + let item = ui.selectable_label(v == current, tl!(l)).on_hover_text(tl!(tip)); + if press.chosen(ui, &item) { *current = v.clone(); changed = true; } - for (v, l, tip) in options { - let item = ui.selectable_label(v == current, tl!(l)).on_hover_text(tl!(tip)); - if press.chosen(ui, &item) { - *current = v.clone(); - changed = true; - } - } - }); + } + }); let response = match take_label_scrub_name(ui, response.response.rect) { Some(label) => response.response.labelled_by(label), None => response.response.accessible_name(name), diff --git a/crates/ui-egui/src/widgets/field_wheel.rs b/crates/ui-egui/src/widgets/field_wheel.rs index 4d2f7ada59..21d37e1bd7 100644 --- a/crates/ui-egui/src/widgets/field_wheel.rs +++ b/crates/ui-egui/src/widgets/field_wheel.rs @@ -101,6 +101,12 @@ pub fn field_gesture_running(ctx: &Context) -> bool { ctx.data(|d| d.get_temp::(gesture_id())).is_some_and(|g| matches!(g.owner, Owner::Field(_)) && now - g.last <= GESTURE_GAP) } +/// Whether [`begin_frame`] handed wheel notches to the focused value field this frame: they step +/// it as the arrow keys do, though the frame's scroll delta no longer shows them. +pub(crate) fn focused_field_wheeled(ctx: &Context) -> bool { + ctx.data(|d| d.get_temp::>(taken_id())).is_some_and(|e| !e.is_empty()) +} + /// Record that value field `id` (whose slot is `field`, as given to [`notches`]) has keyboard /// focus this frame, so the wheel is its next frame. pub fn set_focused(ctx: &Context, id: Id, field: Id) { diff --git a/crates/ui-egui/src/widgets/fields.rs b/crates/ui-egui/src/widgets/fields.rs index c0030bd9c8..4c5cadb278 100644 --- a/crates/ui-egui/src/widgets/fields.rs +++ b/crates/ui-egui/src/widgets/fields.rs @@ -12,6 +12,52 @@ pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts::default(), None).0 } +/// A [`value_field_named`] for whole numbers that says when a typed value was past `range` +/// (Photoshop's "Closest value inserted" alerts, #11938): it stores the closest whole number in +/// range, and returns true once the field is left after such a value was typed, so the caller +/// shows its alert. While the field has the keyboard it keeps the typed text (a `0` on the way to +/// `05` stays). A scrub past the ends just stops there and says nothing. +pub fn value_field_whole_alerting( + ui: &mut Ui, + name: &str, + value: &mut f32, + range: std::ops::RangeInclusive, + suffix: &str, + width: f32, +) -> (Response, bool) { + let (lo, hi) = (*range.start(), *range.end()); + let fit = |v: f32| if v.is_finite() { v.round().clamp(lo, hi) } else { lo }; + *value = fit(*value); + let draft_id = ui.make_persistent_id(egui::IdSalt::new(("whole-alerting-typed", name))); + // Typed text only while its field still has the keyboard: one left without being drawn (a + // tool switch) shows the stored value when it comes back. + let draft = ui.ctx().data(|d| d.get_temp::<(f32, f32, Option)>(draft_id)); + let draft = draft.filter(|(_, stored, field)| *stored == *value && field.is_some_and(|f| ui.ctx().memory(|m| m.has_focus(f)))); + let mut typed = draft.map_or(*value, |(typed, _, _)| typed); + // The field's own range is wide, so the typed value reaches here unclamped. + let r = value_field_named(ui, name, &mut typed, -1.0e9..=1.0e9, suffix, width); + let out_id = r.id.with("out-of-range"); + if r.gained_focus() { + ui.ctx().data_mut(|d| d.remove_temp::(out_id)); + } + if r.changed() && typed.is_finite() { + *value = fit(typed); + let typing = (r.has_focus() || r.lost_focus()) && ui.ctx().dragged_id().is_none(); + let out = typing && !(lo..=hi).contains(&typed); + ui.ctx().data_mut(|d| d.insert_temp(out_id, out)); + if typing && r.has_focus() { + ui.ctx().data_mut(|d| d.insert_temp(draft_id, (typed, *value, Some(r.id)))); + } else { + ui.ctx().data_mut(|d| d.remove_temp::<(f32, f32, Option)>(draft_id)); + } + } + if !r.has_focus() { + ui.ctx().data_mut(|d| d.remove_temp::<(f32, f32, Option)>(draft_id)); + } + let alert = r.lost_focus() && ui.ctx().data_mut(|d| d.remove_temp::(out_id)).unwrap_or(false); + (r, alert) +} + /// A [`value_field`] whose visible caption was drawn apart from it (an options-bar caption in a /// nested layout): `name` names the number when the caption's scrub link did not reach it. pub fn value_field_named(ui: &mut Ui, name: &str, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32) -> Response { diff --git a/crates/ui-egui/src/widgets/press_menu.rs b/crates/ui-egui/src/widgets/press_menu.rs index 16db443c53..1e1962c2e8 100644 --- a/crates/ui-egui/src/widgets/press_menu.rs +++ b/crates/ui-egui/src/widgets/press_menu.rs @@ -154,7 +154,13 @@ impl PressCombo { /// Was option `item` (in the open list `ui`) chosen this frame: clicked, or the press-drag /// gesture that opened the list released on it? The list closes when it was. pub fn chosen(&self, ui: &Ui, item: &Response) -> bool { - let released_on = item.enabled() && item.contains_pointer() && ui.input(|i| i.pointer.primary_released()) && self.owns_gesture(ui.ctx()); + // A release back on the box chooses nothing, also where a list covers the box. + let on_box = |ctx: &egui::Context| { + let at = ctx.input(|i| i.pointer.interact_pos()); + ctx.data(|d| d.get_temp::(gesture_id().with(self.popup))).zip(at).is_some_and(|(b, p)| b.contains(p)) + }; + let released_on = + item.enabled() && item.contains_pointer() && ui.input(|i| i.pointer.primary_released()) && self.owns_gesture(ui.ctx()) && !on_box(ui.ctx()); if released_on { ui.close(); } @@ -169,7 +175,10 @@ impl PressCombo { if pressed && !Popup::is_id_open(ctx, self.popup) { // Opened now, the list counts as open this frame and egui shows it from the next. Popup::open_id(ctx, self.popup); - ctx.data_mut(|d| d.insert_temp(gesture_id(), self.popup)); + ctx.data_mut(|d| { + d.insert_temp(gesture_id(), self.popup); + d.insert_temp(gesture_id().with(self.popup), button.rect); + }); ctx.request_repaint(); } else if self.owns_gesture(ctx) && ctx.input(|i| i.pointer.primary_released() || !i.pointer.primary_down()) { ctx.data_mut(|d| d.remove::(gesture_id())); diff --git a/crates/ui-egui/src/widgets/scrub.rs b/crates/ui-egui/src/widgets/scrub.rs index 8602af4e61..fee418fc03 100644 --- a/crates/ui-egui/src/widgets/scrub.rs +++ b/crates/ui-egui/src/widgets/scrub.rs @@ -63,7 +63,8 @@ fn scrub_option_area(ui: &Ui, label: &Response, tip: Option<&'static str>) { ui.data_mut(|d| d.insert_temp(label_scrub_id(), scrub)); } -pub(super) fn scrub_label_within(ui: &Ui, label: &Response, max_gap: f32) -> Response { +// Shared headers may put a control between the label and its field. +pub(crate) fn scrub_label_within(ui: &Ui, label: &Response, max_gap: f32) -> Response { // Drag only, not focusable: Tab goes to the value field, not to its label as well. let resp = label.interact(Sense::DRAG); let scrub = label_scrub_response(ui, &resp, label.rect, max_gap, Some(label.id)); diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index e85cb758a6..f947226186 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -1401,6 +1401,155 @@ fn dropdown_list_keeps_its_width_while_scrolling() { } } +/// A window `height` tall with the Layers panel's blend mode dropdown (all 27 modes, wheel +/// steps them) `down` from its top, opened. +fn open_blend_modes(height: f32, down: f32) -> Harness<'static, photocraft_color::BlendMode> { + use photocraft_color::BlendMode; + let mut h = Harness::builder().with_size(egui::vec2(400.0, height)).build_ui_state( + move |ui, mode: &mut BlendMode| { + ui.add_space(down); + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + super::dropdown_wheel_hovered(ui, "blend-mode", tl!("Blend Mode"), mode, &opts, 120.0); + }, + BlendMode::Normal, + ); + crate::theme::apply(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run(); + h.get_by_role(egui::accesskit::Role::ComboBox).click(); + h.run_steps(4); + h +} + +/// The open list's rect. +fn open_list(h: &Harness<'_, T>) -> egui::Rect { + let list = h.ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground).find_map(|l| m.area_rect(l.id))); + let Some(list) = list else { panic!("the list is open") }; + list +} + +/// Each mode's row in the open list: its label's last node, as the box shows the chosen one's. +fn mode_rows(h: &Harness<'_, T>) -> Vec { + use photocraft_color::BlendMode; + BlendMode::LAYER_MODES.iter().map(|m| h.get_all_by_label(m.label()).last().map(|n| n.rect()).unwrap_or(egui::Rect::NOTHING)).collect() +} + +/// Photoshop opens the Layers panel's blend modes at full height when the window has room, no +/// scroll bar (#5495): not capped at a fixed height. A short window still scrolls the list, +/// which stays inside the window. +#[test] +fn dropdown_list_is_as_tall_as_its_options_up_to_the_window() { + let h = open_blend_modes(1000.0, 0.0); + let (list, rows) = (open_list(&h), mode_rows(&h)); + for (i, row) in rows.iter().enumerate() { + assert!(list.contains_rect(*row), "row {i} {row:?} shows in the list {list:?}"); + } + let h = open_blend_modes(300.0, 0.0); + let (list, rows) = (open_list(&h), mode_rows(&h)); + assert!(list.top() >= 0.0 && list.bottom() <= 300.0, "the list {list:?} stays in the window"); + assert!(list.height() > 200.0, "the list {list:?} uses the window's height"); + assert!(rows.last().is_some_and(|r| !list.contains_rect(*r)), "the last rows scroll: {rows:?}"); +} + +/// The open list opens at the button's left edge, below the button or above it, never over it +/// (#5495 review: a click released in place would choose the row under the pointer): below +/// when the whole list fits there, else on the side with more room, scrolling when it doesn't +/// fit there either. It stays put while the wheel steps through every mode over it (#1747), +/// although the button widens for the longer names. +#[test] +fn dropdown_list_opens_beside_its_button_and_stays_put_while_the_wheel_steps_its_value() { + use photocraft_color::BlendMode; + // (window height, button's distance from the top, list below it, all modes in sight) + let cases = [ + (1000.0, 0.0, true, true), // room below + (900.0, 420.0, true, false), // room on neither side, more below + (900.0, 520.0, false, false), // room on neither side, more above + (1000.0, 900.0, false, true), // room above only, near the bottom edge + (300.0, 150.0, false, false), // a window shorter than the list + ]; + for (height, down, below, all) in cases { + let mut h = open_blend_modes(height, down); + let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); + let list = open_list(&h); + assert!(list.top() >= 0.0 && list.bottom() <= height, "{height}/{down}: the list {list:?} is in the window"); + assert!((list.left() - button.left()).abs() < 8.0, "{height}/{down}: the list {list:?} starts at the button {button:?}"); + assert!(!list.intersects(button.shrink(1.0)), "{height}/{down}: the list {list:?} leaves the button {button:?} free"); + assert_eq!(list.top() >= button.bottom() - 1.0, below, "{height}/{down}: the list {list:?} is below the button {button:?}"); + let rows = mode_rows(&h); + assert_eq!(rows.iter().all(|r| list.contains_rect(*r)), all, "{height}/{down}: all modes show in {list:?}"); + let over = list.center(); + for _ in 1..BlendMode::LAYER_MODES.len() { + h.hover_at(over); + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run_steps(3); + assert_eq!(open_list(&h), list, "{height}/{down}: the list stays put at {:?}", h.state()); + } + assert_eq!(*h.state(), BlendMode::Luminosity, "{height}/{down}: the wheel stepped through every mode"); + } +} + +/// A short list opens below its button when it fits there, and above it near the window's +/// bottom edge, whole either way. +#[test] +fn a_short_dropdown_list_opens_below_or_above_its_button_whole() { + for (down, below) in [(100.0, true), (360.0, false)] { + let mut h = Harness::builder().with_size(egui::vec2(300.0, 400.0)).build_ui_state( + move |ui, selected: &mut usize| { + ui.add_space(down); + super::dropdown(ui, "blend-mode", tl!("Blend Mode"), selected, &MODES, 120.0); + }, + 0, + ); + h.run(); + h.get_by_role(egui::accesskit::Role::ComboBox).click(); + h.run_steps(4); + let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); + let list = open_list(&h); + assert_eq!(list.top() >= button.bottom() - 1.0, below, "{down}: the list {list:?} is below the button {button:?}"); + assert!(!list.intersects(button.shrink(1.0)), "{down}: the list {list:?} leaves the button {button:?} free"); + for (_, label) in MODES { + let row = h.get_all_by_label(label).last().map(|n| n.rect()).unwrap_or(egui::Rect::NOTHING); + assert!(list.contains_rect(row), "{down}: {label} {row:?} shows in {list:?}"); + } + assert!(list.height() < 150.0, "{down}: the list {list:?} is only as tall as its rows"); + assert_eq!(*h.state(), 0, "{down}: the click chose nothing"); + } +} + +/// In a window with less than 120 pt on either side of the button the list still leaves +/// its button free, scrolling in the room that side has, and stays in the window; the release +/// of the click that opened it, held a few frames, chooses nothing (#5495 review). +#[test] +fn in_a_very_short_window_the_list_still_leaves_its_button_free_and_the_opening_click_chooses_nothing() { + use photocraft_color::BlendMode; + let mut h = Harness::builder().with_size(egui::vec2(400.0, 110.0)).build_ui_state( + |ui, mode: &mut BlendMode| { + ui.add_space(40.0); + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + super::dropdown_wheel_hovered(ui, "blend-mode", tl!("Blend Mode"), mode, &opts, 120.0); + }, + BlendMode::Normal, + ); + h.run(); + let button = h.get_by_role(egui::accesskit::Role::ComboBox).rect(); + let at = button.center(); + h.hover_at(at); + h.run(); + for (pressed, frames) in [(true, 6), (false, 4)] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(frames); + } + let list = open_list(&h); + assert!(!list.intersects(button.shrink(1.0)), "the list {list:?} leaves the button {button:?} free"); + assert!(list.top() >= 0.0 && list.bottom() <= 110.0, "the list {list:?} is in the window"); + assert_eq!(*h.state(), BlendMode::Normal, "the click chose nothing"); +} + const MODES: [(usize, &str); 4] = [(0, "Normal"), (1, "Dissolve"), (2, "Darken"), (3, "Multiply")]; /// A wheel dropdown (or a plain one) of [`MODES`], whose state is the chosen index. diff --git a/crates/ui-egui/src/widgets/tone.rs b/crates/ui-egui/src/widgets/tone.rs index 51cd340a21..58f84dd9fa 100644 --- a/crates/ui-egui/src/widgets/tone.rs +++ b/crates/ui-egui/src/widgets/tone.rs @@ -374,11 +374,10 @@ pub fn histograms(app: &mut PhotocraftApp, source: HistSource, space: ToneSpace) HistSource::BelowLayer(l) | HistSource::Layer(l) | HistSource::UpTo(l) => l, HistSource::Channel { layer, .. } | HistSource::Colors { layer, .. } => layer, }; - let pixels_kept = view_only(st); if let Some((d, l, r, h)) = app.tone_hist.as_mut() && *d == doc_id && *l == layer - && (*r == rev || (*r + 1 == rev && pixels_kept)) + && (*r == rev || pixels_kept_since(st, *r)) && h.tag == want { *r = rev; @@ -391,10 +390,10 @@ pub fn histograms(app: &mut PhotocraftApp, source: HistSource, space: ToneSpace) h } -/// Whether the latest revision changed no pixels (selecting a layer, say): cached histograms of -/// the previous revision still hold (#125). -pub(crate) fn view_only(st: &photocraft_engine::DocState) -> bool { - st.last_damage.is_some_and(|r| r.is_empty()) +/// Whether no pixels changed since revision `seen` (selecting a layer, say): cached histograms of +/// that revision still hold (#125). +pub(crate) fn pixels_kept_since(st: &photocraft_engine::DocState, seen: u64) -> bool { + seen >= st.damage_from() && seen < st.revision && st.last_damage.is_some_and(|r| r.is_empty()) } /// After an editor commits its own adjustment layer, the image below it is unchanged: keep the diff --git a/crates/ui-egui/tests/display_names.rs b/crates/ui-egui/tests/display_names.rs new file mode 100644 index 0000000000..7202a5f91a --- /dev/null +++ b/crates/ui-egui/tests/display_names.rs @@ -0,0 +1,220 @@ +//! Guard the production display surfaces without banning compatibility identifiers or notices. +use std::path::{Path, PathBuf}; + +const BANNED: &[&str] = &[ + "Camera Raw", + "Adobe Single-line Composer", + "Adobe Every-line Composer", + "Adobe PDF Presets", + "Default Photoshop Size", + "All shortcuts reset to Photoshop defaults.", +]; +// Photoshop's own wording where it is stored data or a search alias, never a label: the .atn step +// name Save Actions writes back (the menu item and window read "RAW Develop"), and the names a +// command list is filtered by. +const ALLOWED: &[&str] = &[ + "Adobe Camera Raw Filter", + "Camera Raw Filter", + "Camera Raw Defaults", + "Save these settings as a Camera Raw .xmp file", + "Load settings from a Camera Raw .xmp file", +]; +// The only catalog rows that may say "Camera Raw": their English text names Photoshop's .xmp files. +const ALLOWED_KEYS: &[&str] = &["Save these settings as a Camera Raw .xmp file", "Load settings from a Camera Raw .xmp file"]; +const ROOTS: &[&str] = &["src", "../engine/src"]; + +fn is_word(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + +/// The bans as written, before any exemption: does `text` say one of them as a whole word? +fn mentions_banned(text: &str) -> bool { + BANNED.iter().any(|banned| { + text.match_indices(banned) + .any(|(at, _)| !text[..at].chars().next_back().is_some_and(is_word) && !text[at + banned.len()..].chars().next().is_some_and(is_word)) + }) +} + +fn banned_display(text: &str) -> bool { + !ALLOWED.contains(&text) && mentions_banned(text) +} + +// Read ordinary and raw Rust string literals, ignoring comments. No compiler dependency is +// needed, so this guard can also run by itself when a full application build is unavailable. +#[allow(clippy::cognitive_complexity)] // This small test-only lexer keeps raw-string/comment state together. +fn literals(source: &str) -> Vec { + let chars: Vec = source.chars().collect(); + let mut out = Vec::new(); + let mut at = 0; + let mut test_module = false; + let mut test_depth = 0_usize; + while at < chars.len() { + if chars.get(at..at + 12) == Some(&['#', '[', 'c', 'f', 'g', '(', 't', 'e', 's', 't', ')', ']']) { + at += 12; + let rest: String = chars[at..].iter().collect(); + if rest.trim_start().starts_with("mod ") { + test_module = true; + } + } else if chars.get(at..at + 2) == Some(&['/', '/']) { + while at < chars.len() && chars[at] != '\n' { + at += 1; + } + } else if chars.get(at..at + 2) == Some(&['/', '*']) { + at += 2; + let mut depth = 1; + while at < chars.len() && depth > 0 { + if chars.get(at..at + 2) == Some(&['/', '*']) { + depth += 1; + at += 2; + } else if chars.get(at..at + 2) == Some(&['*', '/']) { + depth -= 1; + at += 2; + } else { + at += 1; + } + } + } else if chars[at] == 'r' && matches!(chars.get(at + 1), Some('"' | '#')) { + let start = at; + at += 1; + while chars.get(at) == Some(&'#') { + at += 1; + } + let hashes = at - start - 1; + if chars.get(at) != Some(&'"') { + continue; + } + at += 1; + let begin = at; + while at < chars.len() { + if chars[at] == '"' && (1..=hashes).all(|n| chars.get(at + n) == Some(&'#')) { + break; + } + at += 1; + } + if !test_module { + out.push(chars[begin..at].iter().collect()); + } + at += 1 + hashes; + } else if chars[at] == '"' { + at += 1; + let mut text = String::new(); + while at < chars.len() { + let c = chars[at]; + at += 1; + if c == '"' { + break; + } + if c == '\\' && at < chars.len() { + text.push(chars[at]); + at += 1; + } else { + text.push(c); + } + } + if !test_module { + out.push(text); + } + } else if chars[at] == '\'' && chars.get(at + 2) == Some(&'\'') { + at += 3; // A character literal such as '"', not the start of a string. + } else { + if test_module { + match chars[at] { + '{' => test_depth += 1, + '}' => { + test_depth = test_depth.saturating_sub(1); + if test_depth == 0 { + test_module = false; + } + } + ';' if test_depth == 0 => test_module = false, + _ => {} + } + } + at += 1; + } + } + out +} + +fn check_tree(path: &Path, failures: &mut Vec) { + if path.is_dir() { + for entry in std::fs::read_dir(path).expect("source directory") { + let path = entry.expect("source entry").path(); + if path.file_name().is_some_and(|name| name == "tests") { + continue; + } + check_tree(&path, failures); + } + } else if path.extension().is_some_and(|ext| ext == "rs") { + let name = path.file_name().expect("source filename").to_string_lossy(); + if name == "tests.rs" || name.ends_with("_tests.rs") { + return; + } + let source = std::fs::read_to_string(path).expect("UTF-8 Rust source"); + // Skip only inline test modules, not later production following test-only imports. + for text in literals(&source) { + if banned_display(&text) { + failures.push(format!("{}: {text:?}", path.display())); + } + } + } +} + +#[test] +fn production_display_names_stay_neutral() { + let base = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut failures = Vec::new(); + for root in ROOTS { + let root = base.join(root); + assert!(root.exists(), "missing display source: {}", root.display()); + check_tree(&root, &mut failures); + } + assert!(failures.is_empty(), "Banned display names:\n{}", failures.join("\n")); +} + +#[test] +fn guard_distinguishes_labels_from_identifiers_and_comments() { + for name in BANNED { + assert!(banned_display(name), "{name}"); + } + for name in ALLOWED { + assert!(!banned_display(name), "{name}"); + } + assert!(!banned_display("filter.cameraRaw")); + assert!(!banned_display("tool.guidedUpright")); + assert!(!banned_display("insert.smartArt")); + assert_eq!(literals("// \"ignored\"\n/* \"ignored\" */ \"label\""), ["label"]); + assert_eq!(literals("r#\"raw label\"#"), ["raw label"]); +} + +#[test] +fn catalogs_do_not_restore_retired_display_names() { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/i18n"); + for entry in std::fs::read_dir(dir).expect("catalog directory") { + let path = entry.expect("catalog entry").path(); + if path.extension().is_none_or(|ext| ext != "tsv") { + continue; + } + let source = std::fs::read_to_string(&path).expect("UTF-8 catalog"); + for line in source.lines().filter(|line| !line.starts_with('#')) { + let columns: Vec<_> = line.split('\t').collect(); + if let [_, key, value] = columns.as_slice() { + assert!(ALLOWED_KEYS.contains(key) || !mentions_banned(key), "{}: retired key {key}", path.display()); + if !ALLOWED_KEYS.contains(key) { + assert!(!mentions_banned(value), "{}: retired display text {value}", path.display()); + } + assert_ne!(*key, "Open in camera raw", "{}: dormant key", path.display()); + } + } + } +} + +#[test] +fn guard_scans_production_after_test_only_items() { + let source = r###"#[cfg(test)] mod tests { let _ = "ignored"; } + #[cfg(test)] use fixtures::Helper; + fn production() { let _ = r#"live label"#; } + "###; + assert_eq!(literals(source), ["live label"]); + assert_eq!(literals("#[cfg(test)] mod tests; fn live() { let _ = \"live label\"; }"), ["live label"]); +} diff --git a/crates/ui-egui/tests/it/background_eraser_reset_tip.rs b/crates/ui-egui/tests/it/background_eraser_reset_tip.rs new file mode 100644 index 0000000000..f971412bc4 --- /dev/null +++ b/crates/ui-egui/tests/it/background_eraser_reset_tip.rs @@ -0,0 +1,113 @@ +//! #11911: Reset Tool gives the Background Eraser the reference application's tip, a 13 px hard +//! round at 25 % spacing with Size control off, not the 20 px default at 10 %; Reset All Tools and +//! a first use do too. The other painting tools and `paint.stroke` without a `brush` keep theirs. + +use photocraft_ui_egui::control::{ControlRequest, handle}; +use photocraft_ui_egui::{PhotocraftApp, Tool}; +use serde_json::{Value, json}; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app +} + +/// A control request as the control channel sends it, then the frame's sync. +fn control(app: &mut PhotocraftApp, method: &str, params: Value) -> Value { + let ctx = egui::Context::default(); + let (req, rx) = ControlRequest::new(method, params); + handle(app, &ctx, &req); + app.sync_views(); + rx.try_recv().unwrap_or(Value::Null) +} + +/// Pick `tool`, and swap its brush in as a frame does. +fn pick(app: &mut PhotocraftApp, tool: Tool) { + app.ui.tool = tool; + photocraft_ui_egui::paint_mouse::sync_tool_brush(app); + app.sync_views(); +} + +/// Size, hardness, spacing, angle and roundness of the live brush, as `brush.get` reports them. +fn tip(app: &mut PhotocraftApp) -> [f64; 5] { + let b = app.run("brush.get", json!({})).unwrap(); + ["size", "hardness", "spacing", "angle", "roundness"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4) +} + +fn pressure_size(app: &mut PhotocraftApp) -> bool { + app.run("brush.get", json!({})).unwrap()["pressureSize"].as_bool().unwrap() +} + +/// A tip that is neither default, so a reset has something to undo. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness, b.pressure_size) = (57.0, 0.4, 0.6, 30.0, 0.5, true); +} + +const ERASER_TIP: [f64; 5] = [13.0, 1.0, 0.25, 0.0, 1.0]; +const DEFAULT_TIP: [f64; 5] = [20.0, 1.0, 0.1, 0.0, 1.0]; + +#[test] +fn reset_tool_gives_the_background_eraser_a_13_px_hard_tip() { + let mut app = app(); + pick(&mut app, Tool::BackgroundEraser); + scramble(&mut app); + control(&mut app, "ui.menu.invoke", json!({"id": "tool.reset"})); + assert_eq!(tip(&mut app), ERASER_TIP); + assert!(!pressure_size(&mut app), "Size control Off"); + // The options-bar brush chip shows the brush's size. + assert_eq!(app.session.tools.brush.size.round(), 13.0); +} + +#[test] +fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { + let mut app = app(); + pick(&mut app, Tool::BackgroundEraser); + scramble(&mut app); + control(&mut app, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); + assert_eq!(tip(&mut app), ERASER_TIP, "active"); + assert!(!pressure_size(&mut app), "Size control Off, active"); + let mut app = self::app(); + pick(&mut app, Tool::BackgroundEraser); + scramble(&mut app); + pick(&mut app, Tool::Pencil); + control(&mut app, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); + pick(&mut app, Tool::BackgroundEraser); + assert_eq!(tip(&mut app), ERASER_TIP, "picked after the reset"); + assert!(!pressure_size(&mut app), "Size control Off, picked after the reset"); +} + +#[test] +fn a_first_use_starts_with_the_tip() { + // No stored tool brushes: the Background Eraser's first pick, after another tool's tip. + let mut app = app(); + pick(&mut app, Tool::Pencil); + scramble(&mut app); + pick(&mut app, Tool::BackgroundEraser); + assert_eq!(tip(&mut app), ERASER_TIP); + assert!(!pressure_size(&mut app)); + // Its own tip is then kept across tool switches. + app.session.tools.brush.size = 42.0; + pick(&mut app, Tool::Pencil); + pick(&mut app, Tool::BackgroundEraser); + assert_eq!(tip(&mut app)[0], 42.0); +} + +#[test] +fn other_tools_and_session_strokes_keep_their_tips() { + for tool in [Tool::Pencil, Tool::Eraser] { + let mut a = app(); + pick(&mut a, tool); + scramble(&mut a); + control(&mut a, "ui.menu.invoke", json!({"id": "tool.reset"})); + assert_eq!(tip(&mut a), DEFAULT_TIP, "{tool:?}"); + } + let mut app = app(); + assert_eq!(tip(&mut app), DEFAULT_TIP, "what `paint.stroke` / `paint.backgroundEraser` paint with when no `brush` is given"); + // A first use of another tool still takes the current tip, as before. + pick(&mut app, Tool::Pencil); + scramble(&mut app); + pick(&mut app, Tool::Eraser); + assert_eq!(tip(&mut app)[0], 57.0); +} diff --git a/crates/ui-egui/tests/it/healing_reset_tip.rs b/crates/ui-egui/tests/it/healing_reset_tip.rs new file mode 100644 index 0000000000..c783b0fa28 --- /dev/null +++ b/crates/ui-egui/tests/it/healing_reset_tip.rs @@ -0,0 +1,138 @@ +//! #12099: Reset Tool gives the Healing Brush the reference application's tip, a 19 px hard round +//! at 25 % spacing, not the 20 px default at 10 %; Reset All Tools and a first use do too. The +//! Clone Stamp, the Spot Healing Brush and commands without brush params keep theirs. + +use photocraft_ui_egui::control::{ControlRequest, handle}; +use photocraft_ui_egui::{PhotocraftApp, Tool}; +use serde_json::{Value, json}; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app +} + +/// A control request as the control channel sends it, then the frame's sync. +fn control(app: &mut PhotocraftApp, method: &str, params: Value) -> Value { + let ctx = egui::Context::default(); + let (req, rx) = ControlRequest::new(method, params); + handle(app, &ctx, &req); + app.sync_views(); + rx.try_recv().unwrap_or(Value::Null) +} + +/// Pick `tool`, and swap its brush in as a frame does. +fn pick(app: &mut PhotocraftApp, tool: Tool) { + app.ui.tool = tool; + photocraft_ui_egui::paint_mouse::sync_tool_brush(app); + app.sync_views(); +} + +/// Size, hardness, spacing, angle and roundness of the live brush, as `brush.get` reports them. +fn tip(app: &mut PhotocraftApp) -> [f64; 5] { + let b = app.run("brush.get", json!({})).unwrap(); + ["size", "hardness", "spacing", "angle", "roundness"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4) +} + +/// A tip that is neither default nor the Healing Brush's, so a reset has something to undo. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness) = (57.0, 0.4, 0.6, 30.0, 0.5); +} + +const HEALING_TIP: [f64; 5] = [19.0, 1.0, 0.25, 0.0, 1.0]; +const DEFAULT_TIP: [f64; 5] = [20.0, 1.0, 0.1, 0.0, 1.0]; + +#[test] +fn reset_tool_gives_the_healing_brush_a_19_px_hard_tip() { + let mut app = app(); + pick(&mut app, Tool::Healing); + scramble(&mut app); + control(&mut app, "ui.menu.invoke", json!({"id": "tool.reset"})); + assert_eq!(tip(&mut app), HEALING_TIP); + // The options-bar brush chip paints the live brush's `size.round()` as plain text (no + // accessibility label carries it), so this is the number it reads. + assert_eq!(app.session.tools.brush.size.round(), 19.0); +} + +#[test] +fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { + let mut app = app(); + pick(&mut app, Tool::Healing); + scramble(&mut app); + control(&mut app, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); + assert_eq!(tip(&mut app), HEALING_TIP, "active"); + let mut app = self::app(); + pick(&mut app, Tool::Healing); + scramble(&mut app); + pick(&mut app, Tool::Pencil); + control(&mut app, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); + pick(&mut app, Tool::Healing); + assert_eq!(tip(&mut app), HEALING_TIP, "picked after the reset"); +} + +#[test] +fn a_first_use_starts_with_the_tip() { + // No stored tool brushes, as on a fresh install: the Healing Brush's first pick, after another + // tool's tip. + let mut app = app(); + pick(&mut app, Tool::Pencil); + scramble(&mut app); + pick(&mut app, Tool::Healing); + assert_eq!(tip(&mut app), HEALING_TIP); + // Its own tip is then kept across tool switches. + app.session.tools.brush.size = 42.0; + pick(&mut app, Tool::Pencil); + pick(&mut app, Tool::Healing); + assert_eq!(tip(&mut app)[0], 42.0); +} + +#[test] +fn other_retouch_tools_and_session_strokes_keep_their_tips() { + for tool in [Tool::CloneStamp, Tool::SpotHealing] { + let mut a = app(); + pick(&mut a, tool); + scramble(&mut a); + control(&mut a, "ui.menu.invoke", json!({"id": "tool.reset"})); + assert_eq!(tip(&mut a), DEFAULT_TIP, "{tool:?}"); + // A first use still takes the current tip, as before. + let mut a = app(); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + pick(&mut a, tool); + assert_eq!(tip(&mut a)[0], 57.0, "{tool:?}, first use"); + } +} + +/// The layer's pixels after `cmd` paints a short stroke in a fresh session, with `brush` params +/// added. The Healing Brush gets a black line to sample, as white healed into white is white +/// whatever the tip. +fn stroke(cmd: &str, brush: Value) -> Vec { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200, "background": "white"})).unwrap(); + let mut p = json!({"points": [[100, 100], [140, 100]]}); + if cmd == "paint.healingBrush" { + s.execute("paint.stroke", json!({"points": [[50, 60], [110, 60]], "color": "#000000", "brush": {"size": 6}})).unwrap(); + p["offset"] = json!([-40, -40]); + } + p.as_object_mut().unwrap().extend(brush.as_object().unwrap().clone()); + s.execute(cmd, p).unwrap(); + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(st.doc.bounds()) +} + +#[test] +fn commands_without_brush_params_paint_with_the_default_brush() { + // `paint.healingBrush` takes its tip as percent scalars, `paint.stroke` as a `brush` object. + let cases = [ + ("paint.healingBrush", json!({"size": 20, "hardness": 100, "spacing": 10}), json!({"size": 19, "hardness": 100, "spacing": 25})), + ("paint.stroke", json!({"brush": {"size": 20, "hardness": 1.0, "spacing": 0.1}}), json!({"brush": {"size": 19, "hardness": 1.0, "spacing": 0.25}})), + ]; + for (cmd, default_tip, healing_tip) in cases { + let default = stroke(cmd, default_tip); + assert!(stroke(cmd, json!({})) == default, "{cmd}"); + // The pixels tell the Healing Brush's reset tip apart, so the comparison would catch it. + assert!(stroke(cmd, healing_tip) != default, "{cmd}"); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 41d3f3e662..d6efa1f5d0 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -5,6 +5,7 @@ mod actions_panel_menu; mod actions_record_again; mod adjust_preview_gpu; mod arbitrary_rotation_preview; +mod background_eraser_reset_tip; mod batch_export_options; mod brush_reset_defaults; mod camera_raw_histogram; @@ -33,6 +34,7 @@ mod export_as_scaling; mod eyedropper_ring; mod full_res_preview; mod gpu_device_loss; +mod healing_reset_tip; mod layout_perf; mod live_stroke_canvas; mod magnetic_lasso_right_click; diff --git a/docs/atn.md b/docs/atn.md index be7eca3787..f169b86132 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -190,7 +190,7 @@ row; the action still adds only one Undo entry. | (string ID only) | smartBrushWorkspace | Select and Mask | `select.refineEdge` | | (string ID only) | autoCutout | Select Subject | `select.subject` | | `SlcC` | selectiveColor | Selective Color | `image.adjustments.selectiveColor` | -| `setd` | set | Set | `select.all`, `select.deselect`, `select.reselect`, `select.loadSelection`, `select.rect`, `select.lasso`, `select.editInQuickMaskMode`, `tools.setColors`, `layer.setProps`, `layer.renameLayer`, `layer.setLabelColor`, `layer.setAdjustment`, `layer.fill.pattern.set`, `gradient.fill.set`, `layer.new.layerFromBackground`, `layer.layerStyle.blendingOptions`, `layer.smartFilter.blendingOptions` | +| `setd` | set | Set | `select.all`, `select.deselect`, `select.reselect`, `select.loadSelection`, `select.rect`, `select.lasso`, `select.editInQuickMaskMode`, `tools.setColors`, `layer.setProps`, `layer.renameLayer`, `layer.setLabelColor`, `layer.setAdjustment`, `layer.fill.pattern.set`, `gradient.fill.set`, `layer.new.layerFromBackground`, `layer.layerStyle.blendingOptions`, `layer.smartFilter.blendingOptions`, `image.analysis.setMeasurementScale` (Set Measurement Scale › Custom) | | (string ID only) | adaptCorrect | Shadows/Highlights | `image.adjustments.shadowsHighlights` | | `Shrp` | sharpen | Sharpen | `filter.sharpen.sharpen` | | `ShrE` | sharpenEdges | Sharpen Edges | `filter.sharpen.sharpenEdges` | @@ -315,6 +315,18 @@ The separate `CropPhotos0001` helper remains a complete kept Photoshop step. Playback stops at that enabled helper before subsequent duplicate/crop steps can run. This covers the parent event, not complete recordings with generated helpers. +Set Measurement Scale › Custom is a Set of the target document's `measurementScale` +property. `T ` holds `pixelLength` (a long above 0), `logicalLength` (a double +above 0) and `logicalUnits` (text that isn't blank), and the step plays as +`image.analysis.setMeasurementScale` with preset `custom`. A loaded step saves back +its recorded descriptor while it still sets the same scale. A step recorded in +PhotoCraft writes `T ` with class `measurementScale`, since the recordings don't +pin that class down. Another target, another value type, a missing or extra key, or +a value the native command refuses stays a kept step. A native step that reads the +scale, resets it to the default, leaves a value to the current scale or has a +fractional pixel length refuses export. Place Scale Marker (a script step) stays a +kept step. + ### Perspective Warp recordings `perspectiveWarpTransform` maps Layout and Warp to one `edit.perspectiveWarp` diff --git a/docs/average-filter.md b/docs/average-filter.md new file mode 100644 index 0000000000..65e91a8433 --- /dev/null +++ b/docs/average-filter.md @@ -0,0 +1,74 @@ +# Average filter: transparency reference + +The Average filter replaces colour while retaining each pixel's transparency. +Two synthetic cases were executed in Photoshop **26.6.1 on Windows x64** on +2026-10-23. These are observations of RGB8 raster layers, without a selection or +transparency lock; they are not a claim of parity in other colour modes or at +other bit depths. + +Each input is a 16 × 16 RGBA PNG. Its left eight columns are red and its right +eight columns are blue. Open it in Photoshop, run Filter › Blur › Average, and +save a PNG copy. Inspect the file's RGBA values, including invisible colours. + +| Input left / right RGBA | Output left / right RGBA | +|---|---| +| `(255,0,0,255)` / `(0,0,255,0)` | `(128,0,128,255)` / `(128,0,128,0)` | +| `(255,0,0,64)` / `(0,0,255,192)` | `(128,0,128,64)` / `(128,0,128,192)` | + +An opaque control produces `(128,0,128,255)` throughout. Thus transparency is +neither a weight in this colour average nor a channel to replace with its mean. + +PhotoCraft previously alpha-weighted the RGB mean and replaced alpha with its +mean. On the first case that predicts translucent red throughout, rather than +purple pixels with their original transparency. The fix uses selection coverage +for the existing mean and leaves each pixel's alpha alone. Selection mixing and +the existing colour conversion path are unchanged. In particular, this does not +establish Photoshop parity for feathered selection weighting or CMYK/Lab means. + +The engine tests construct their own pixels; no Photoshop binary, proprietary +code, or reference image is included. They cover transparent and partially +transparent pixels, selection boundaries, one history step, undo and redo at +8/16/32-bit storage. The higher-depth tests establish PhotoCraft invariants; +the external reference measurements above are RGB8 only. + +Run the focused regressions with: + +```sh +cargo test -p photocraft-engine --lib average_preserves +``` + +## Smart filters + +The PSD importer already recognizes the optionless `Avrg` descriptor (see +[#6297](https://github.com/storytold/photocraft/pull/6297)). Recognition alone did +not execute it: the shared renderer returned `None`, leaving the source pixels +unchanged, and the raster-only command was disabled on Smart Objects. + +Average now uses the shared filter command and algorithm. It can be added to a +Smart Object, toggled, undone and redone, or re-rendered from an imported record. +The raster path retains its canvas limit, selection weighting and alpha behavior. +Like other core filters, new invocations validate parameters before editing. + +The integration tests create their own red/blue Smart Objects at RGB8/16/32f. +They check the dispatcher, command enablement, one history step, visibility, +undo/redo, and re-rendering after clearing both the layer and stage caches: + +```sh +cargo test -p photocraft-engine --test it average_smart +``` + +An additional, explicitly ignored test accepts a local Photoshop oracle. To +reproduce it in Photoshop, create an opaque 16 × 16 RGB8 image with eight red +columns followed by eight blue columns, convert the layer to a Smart Object, +apply Average and save a PSD. Photoshop 26.6.1 on Windows produces purple +`(128,0,128,255)` throughout. Then run, in PowerShell: + +```powershell +$env:PHOTOCRAFT_AVERAGE_PSD = 'C:\path\to\average-smart.psd' +cargo test -p photocraft-engine --test it average_photoshop_psd_rerenders_from_source -- --ignored --nocapture +``` + +This test discards the imported layer cache and the smart-filter stage cache, +then rebuilds from the embedded source. Merely importing or flattening the PSD +would reuse Photoshop's saved pixels and would not prove execution. The local +PSD is not committed and the opt-in test does not raise a corpus floor. diff --git a/docs/brush-parity.md b/docs/brush-parity.md index acd93b311e..99501ca8d5 100644 --- a/docs/brush-parity.md +++ b/docs/brush-parity.md @@ -1,6 +1,6 @@ # Brush and painting parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Angle/Roundness fields left of the Brush Tip Shape widget, labels right-aligned, #3825 partial; the eraser end of the pen switches to the Eraser on Windows with Windows Ink on, #2285; no estimate changed; Art History Brush Opacity on the options bar, #10263; no estimate changed; Shift+right-click menu for every painting tool: Edit Brush… and the tool's own Mode list; Brush Shift+right-click Mode picker and Escape dismissal; Art History Brush row added as partial, 8 of 10 styles, TOOL-213-20, #1610; hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; Mode for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; named, stateful Brush Settings locks and visible keyboard focus; independent Brush Pose tilt-axis overrides; Transfer Wetness/Mix tool applicability; dragged preset tip preview; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view; Color Replacement is a live toolbar tool; no brush-feel estimate changed; 2026-10-11: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Both Axes on Scatter headers, #3825 partial; Brush Tip Shape Spacing checkbox and percentage share one header, #3825 partial; Angle/Roundness fields left of the Brush Tip Shape widget, labels right-aligned, #3825 partial; the eraser end of the pen switches to the Eraser on Windows with Windows Ink on, #2285; no estimate changed; Art History Brush Opacity on the options bar, #10263; no estimate changed; Shift+right-click menu for every painting tool: Edit Brush… and the tool's own Mode list; Brush Shift+right-click Mode picker and Escape dismissal; Art History Brush row added as partial, 8 of 10 styles, TOOL-213-20, #1610; hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; Mode for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; named, stateful Brush Settings locks and visible keyboard focus; independent Brush Pose tilt-axis overrides; Transfer Wetness/Mix tool applicability; dragged preset tip preview; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view; Color Replacement is a live toolbar tool; no brush-feel estimate changed; 2026-10-11: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026 Painting is where Photoshop users notice differences first, so it gets its own checklist: the brush engine (`crates/paint/src/brush.rs`), the Brush Settings UI @@ -19,9 +19,11 @@ tablets against Photoshop side by side. | Section | Status | Evidence | |---|---|---| | Brush Tip Shape: size, angle, roundness, hardness, spacing, flip X/Y | done | `brush.rs` | +| Brush Tip Shape Spacing checkbox and percentage share one header without a duplicated label | done | #3825 (Spacing header only); UI regressions cover all 14 themes, enabled/disabled editing, percentage limits, fractional-value retention and `tools.setBrush` routing. | | Brush Tip Shape places aligned Angle/Roundness controls left of the interactive widget | done | #3825 (Angle/Roundness layout only); UI regressions cover 14 themes at two panel widths, imported-value retention, numeric limits, actual arrow/handle gestures and existing command routing. | | Shape Dynamics (size/angle/roundness jitter, pen pressure/tilt/rotation/wheel controls, minimums, flip jitter, brush projection) | done | #174 | | Scattering (both axes, count, count jitter) | done | | +| Scattering and Dual Brush place Both Axes between the Scatter label and percentage | done | #3825 (Both Axes header placement only); all-theme UI regressions cover both axis values, fractional-value retention, percentage limits, label scrubbing, amount-track edits and existing command routing. | | Texture (pattern, scale, brightness, contrast, mode, depth, each tip) | done | | | Dual Brush | done | | | Color Dynamics (FG/BG, hue/sat/brightness jitter, purity, per tip) | done | | @@ -134,7 +136,9 @@ tablets against Photoshop side by side. | 2026-10-12 | minor | A shaped tip's cursor outline turns and flips with a rotated or flipped view, and follows pixel aspect correction | | 2026-10-13 | minor | Shape Dynamics and Transfer minimum inputs follow their Control and retain their values while disabled (#3825, partial). No brush-feel estimate changed. | | 2026-10-13 | minor | Hue Jitter uses the same themed amount slider as other jitter controls (#3825, partial). No brush-feel estimate changed. | +| 2026-10-13 | minor | Brush Tip Shape combines the Spacing checkbox and percentage into one header (#3825, partial), retaining the value while disabled. No brush-feel estimate changed. | | 2026-10-13 | minor | Brush-only Shift+right-click Mode menu shares options-bar choices, including Clear; preserves existing right-click gestures and consumes outside dismissal without painting (#4929). No brush-feel estimate changed. | +| 2026-10-13 | minor | Scattering and Dual Brush place Both Axes on the shared Scatter header (#3825, partial), preserving label scrubbing and values. No brush-feel estimate changed. | | 2026-10-13 | minor | Angle/Roundness controls use right-aligned labels in the left column, with the interactive widget on the right (#3825, partial). Units, limits and gestures retained; no brush-feel estimate changed. | | 2026-10-13 | minor | Transfer Wetness/Mix controls follow the active tool and retain their settings while disabled (#3825, partial). No brush-feel estimate changed. | | 2026-10-14 | minor | The 12 existing Brush Settings section locks expose translated names and locked state to AccessKit and show themed keyboard focus (#3477 workflow); icons, hit targets and command behavior retained. No brush-feel estimate changed. | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3c438901e4..95c70bf0ee 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -46,8 +46,8 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - `engine.execute {command, params}`: run any engine or UI command by id. Engine commands run directly with their default params and never open a dialog. Use `ui.menu.invoke` for menu-click behaviour, which opens a command's dialog when no params are given. `params` must be a JSON object (omit it or pass `null` for none); an array, string, number or boolean is an error naming the command, in every transport (control channel, `serve`, MCP and the CLI) - `engine.commands`: list commands with enablement; the `result` is a JSON array of command objects (see [Command list replies](#command-list-replies)) -- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, window size). The menu tree is not included; use `ui.menu.list`. `brushPicker` is `null` while closed and `{pos: [x, y], size: [w, h]?, list: {collapsed, filter, renaming, showName, showStroke, showTip, scale}}` while the Brush Preset picker is open (coordinates in screen points; `size` is the picker's content size once its corner grip was dragged, `null` before that, and the drag remembers both dimensions; the three `show*` flags pick the parts of each preset's card — at least one is always on; `scale` is the footer slider, 0.15–2 with 1 the standard, multiplying the cards' width and height — the heights stop at half size and the name and tip-size text hold their 1.0 size — and dropping the tips' size numbers at 0.40 and below; the parts and the scale are remembered across restarts, while the search, collapsed groups and a rename in progress are not). `view` holds the View/Window/Type preferences: `screen_mode`, `extras`, `show` and `snap_to` flags, `flip_horizontal`, `arrange` (Window › Arrange layout), pixel aspect, font preview size, language options. `perf.timings.gpuInfo` holds the graphics adapter, backend, driver, the backend chosen at launch and why, the canvas renderer (`gpu`/`cpu`) and, after a device loss, `lost` (`help.systemInfo` returns the same as `info`). `perf.renderPath` says why the active document is drawn on the CPU: `current` is `null` on the GPU, else `{doc, kind, detail}` (`kind` is one of `overBudget`, `canvasTooLarge`, `compositorBuild`, `deviceLost`, `gpuError`, `unsupported`, `adjustPreview`, `viewTransform`, `softwareAdapter`, `cpuMode`; `detail` is the English reason, with the working set and budget for `overBudget`), and `history` holds the last 32 changes, oldest first (`{t, doc, kind, detail}`, `kind` `null` for back on the GPU, `doc` the changed document's id, or 0 for a change to every document). An adjustment dialog's CPU proxy preview has its own slot: `current` reports it (`adjustPreview`) only when neither the window nor the canvas has a reason, it isn't recorded while the whole window is off the GPU, and its history entries always have `kind` `adjustPreview`, with `detail` `null` when the preview stops using the proxy (never read as back on the GPU). `perf.timings.gpuFallback` is `current`'s `detail` as text. `perf.slowFrames` lists the last 64 frames over 50 ms, oldest first, each with its stages in ms: `t` (start), `frameMs`, `inputMs` (raw input to the UI build, commands excluded), `commandMs` and `command` (the last command run since the previous frame), `damageMs` (damage tracking and GPU memory budgeting), `compositeMs`, `uploadMs`, `gpuMs` (the GPU's own composite time, or `null`), `presentMs` (the previous frame's tessellation and submission, or `null`), `refresh` and `refreshPx` (the canvas redraw's kind and pixels) and `path` (`gpu` or `cpu`). It stays empty on the web, which has no clock -- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, filterMaskTarget?, selectionMode?, zoom?, center?, rotation?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerName?, brushPickerStroke?, brushPickerTip?, brushPickerScale?, gradientBlendMode?, gradientClassic?, shapeStroke?}`: change UI state; any other field is an error, checked before anything changes (`zoom` is the canvas zoom where 1 = 100%, one document pixel per physical display pixel, so a scaled display doesn't magnify the image; `theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `brushesView` is `list` or `grid` for the Brushes panel; `brushPickerName`, `brushPickerStroke` and `brushPickerTip` are the Brush Preset picker's card parts (booleans, at least one on), and `brushPickerScale` its footer card-scale slider (0.15 to 2, 1 the standard); `brushPicker` is `[x, y]` in screen points to open the Brush Preset picker there (as a right-click with a painting tool does) or `null` to close it, and picking a preset in it is `tools.setBrush {"preset": name}`; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"], tabOrder: {"layers": ["Paths", "Layers", "Channels"]}}`, the right-dock groups top to bottom, their heights in points, the groups collapsed to their tab strip and each group's tab order left to right by panel name (a group left out keeps its default order, unknown names are ignored and tabs not listed follow in their default order; `dockTabs` keeps indexing tabs in their default order); `dockWidth` sets the right dock width in points, clamped to 250..520; `colorPanel` is `{background?, mode?, ramp?, webSafeRamp?}`, merged into the Color panel's state: `background` is whether it edits the background colour, `mode` its panel-menu display (`hueCube`, `brightnessCube`, `colorWheel`, `grayscaleSlider`, `rgbSliders`, `hsbSliders`, `cmykSliders`, `labSliders` or `webColorSliders`), `ramp` the colour ramp under the sliders (`rgbSpectrum`, `cmykSpectrum`, `grayscaleRamp` or `currentColors`) and `webSafeRamp` Make Ramp Web Safe; `maskTarget` targets the active layer's mask, which, like Photoshop, swaps in the foreground/background pair kept for masks (white/black until one is picked) and swaps the pixels' pair back when the pixels are targeted again; `filterMaskTarget` targets the active smart object's filter mask (an error without smart filters), so painting, fills, filters and adjustments edit it (`"target":"filterMask"`) while Move and Edit › Transform still act on the smart object) +- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, window size). The menu tree is not included; use `ui.menu.list`. `brushPicker` is `null` while closed and `{pos: [x, y], size: [w, h]?, list: {collapsed, filter, renaming, showName, showStroke, showTip, scale}}` while the Brush Preset picker is open (coordinates in screen points; `size` is the picker's content size once its corner grip was dragged, `null` before that, and the drag remembers both dimensions; the three `show*` flags pick the parts of each preset's card — at least one is always on; `scale` is the footer slider, 0.15–2 with 1 the standard, multiplying the cards' width and height — the heights stop at half size and the name and tip-size text hold their 1.0 size — and dropping the tips' size numbers at 0.40 and below; the parts and the scale are remembered across restarts, while the search, collapsed groups and a rename in progress are not). `view` holds the View/Window/Type preferences: `screen_mode`, `extras`, `show` and `snap_to` flags, `flip_horizontal`, `arrange` (Window › Arrange layout), pixel aspect, font preview size, language options. `perf.timings.gpuInfo` holds the graphics adapter, backend, driver, the backend chosen at launch and why, the canvas renderer (`gpu`/`cpu`) and, after a device loss, `lost` (`help.systemInfo` returns the same as `info`). `perf.renderPath` says why the active document is drawn on the CPU: `current` is `null` on the GPU, else `{doc, kind, detail}` (`kind` is one of `overBudget`, `canvasTooLarge`, `compositorBuild`, `deviceLost`, `gpuError`, `unsupported`, `adjustPreview`, `viewTransform`, `softwareAdapter`, `cpuMode`; `detail` is the English reason, with the working set and budget for `overBudget`), and `history` holds the last 32 changes, oldest first (`{t, doc, kind, detail}`, `kind` `null` for back on the GPU, `doc` the changed document's id, or 0 for a change to every document). An adjustment dialog's CPU proxy preview has its own slot: `current` reports it (`adjustPreview`) only when neither the window nor the canvas has a reason, it isn't recorded while the whole window is off the GPU, and its history entries always have `kind` `adjustPreview`, with `detail` `null` when the preview stops using the proxy (never read as back on the GPU). `perf.timings.gpuFallback` is `current`'s `detail` as text. `perf.slowFrames` lists the last 64 frames over 50 ms, oldest first, each with its stages in ms: `t` (start), `frameMs`, `inputMs` (raw input to the UI build, commands excluded), `commandMs` and `command` (the last command run since the previous frame), `damageMs` (damage tracking and GPU memory budgeting), `compositeMs`, `uploadMs`, `gpuMs` (the GPU's own composite time, or `null`), `presentMs` (the previous frame's tessellation and submission, or `null`), `refresh` and `refreshPx` (the canvas redraw's kind and pixels) and `path` (`gpu` or `cpu`). The web build keeps them too (its clock is `performance.now()`) and logs them to the browser console +- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, filterMaskTarget?, selectionMode?, zoom?, center?, rotation?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerName?, brushPickerStroke?, brushPickerTip?, brushPickerScale?, gradientBlendMode?, gradientClassic?, shapeStroke?}`: change UI state; any other field is an error, checked before anything changes (`zoom` is the canvas zoom where 1 = 100%, one document pixel per physical display pixel, so a scaled display doesn't magnify the image; `theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `brushesView` is `list` or `grid` for the Brushes panel; `brushPickerName`, `brushPickerStroke` and `brushPickerTip` are the Brush Preset picker's card parts (booleans, at least one on), and `brushPickerScale` its footer card-scale slider (0.15 to 2, 1 the standard); `brushPicker` is `[x, y]` in screen points to open the Brush Preset picker there (as a right-click with a painting tool does) or `null` to close it, and picking a preset in it is `tools.setBrush {"preset": name}`; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"], tabOrder: {"layers": ["Paths", "Layers", "Channels"]}}`, the right-dock groups top to bottom, their heights in points, the groups collapsed to their tab strip and each group's tab order left to right by panel name (a group left out keeps its default order, unknown names are ignored and tabs not listed follow in their default order; `dockTabs` keeps indexing tabs in their default order); `dockWidth` sets the whole end dock's width in points, requested within 250..max(520, window width − 400): the change from the current width is shared equally among the columns, within their minimums and iconic caps (a column that reaches one passes the rest to the others), so those determine the achieved model width; `dockWidth` is the requested model width, and in a window too narrow for it, in either layout, the drawn dock may be narrower, clipped to its panel so the toolbar and the canvas's 200 points stay clear, and it is drawn at the stored width again when the window grows; `colorPanel` is `{background?, mode?, ramp?, webSafeRamp?}`, merged into the Color panel's state: `background` is whether it edits the background colour, `mode` its panel-menu display (`hueCube`, `brightnessCube`, `colorWheel`, `grayscaleSlider`, `rgbSliders`, `hsbSliders`, `cmykSliders`, `labSliders` or `webColorSliders`), `ramp` the colour ramp under the sliders (`rgbSpectrum`, `cmykSpectrum`, `grayscaleRamp` or `currentColors`) and `webSafeRamp` Make Ramp Web Safe; `maskTarget` targets the active layer's mask, which, like Photoshop, swaps in the foreground/background pair kept for masks (white/black until one is picked) and swaps the pixels' pair back when the pixels are targeted again; `filterMaskTarget` targets the active smart object's filter mask (an error without smart filters), so painting, fills, filters and adjustments edit it (`"target":"filterMask"`) while Move and Edit › Transform still act on the smart object) - `typeTransform` is `null` outside a temporary Ctrl/Cmd Type-tool drag. During a drag it reports its source document/revision, original affine, oriented `frame` (layer, local bounds, document-space corners and pivot), and captured `gesture`. Drive it with `ui.pointer` and `command: true` at `down`; `move`/`up` may release the modifier. The document/history remain unchanged during preview, and `up` applies one `type.edit` within `textEdit`'s session. Pressing Escape during the drag cancels only the preview. This pointer state is never restored from saved UI state. - `ui.menu.invoke {id, params?, wait?}` / `ui.menu.list`: activate a menu item by id; list the menu tree. A menu item that starts a background job (a filter without a dialog, such as Blur More) replies with the job's result once it has been applied; with `"wait": false` the reply is `{job, pending: true}` at once. Window ends with the open documents as `window.document.` (tab order, the active one checked, #2991); invoking one brings that document to the front and replies `{document: index}`. Camera Raw and the full-window workspaces (Liquify, Content-Aware Fill, Filter Gallery, Adaptive Wide Angle) are modal: while one is open, `ui.menu.invoke` refuses every other menu item ("menu command is unavailable while a modal dialog is open") and accepts only that workspace's own `{"ui": {...}}` requests (`filter.liquify`, `edit.contentAwareFill`, `filter.filterGallery`, `filter.adaptiveWideAngle`, `filter.cameraRaw`; `params` must hold only the `ui` object), so finish it with `{"ui":{"commit":true}}` or `{"ui":{"cancel":true}}` first. Those requests are refused too while a dialog, an unsaved-changes prompt or a crop that blocks the command is open: resolve that first, then commit or cancel the workspace. `ui.menu.list` reports the same gate: an item the modal state refuses is listed with `enabled: false`. `engine.execute` is not a menu click and is not gated - `ui.set` also accepts `gradientBlendMode` (a layer blend mode name, such as `Difference`) and `gradientClassic` (boolean) for the Gradient tool options bar. @@ -73,7 +73,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - Gradient Overlay color stops use `colorPicker {parent, effect, field: "stops", stop: index}`; the stop must exist. - `ui.dialog.open {kind:"colorPicker", textStyle:{kind:"character"|"paragraph", id:u32}}` opens the shared Color Picker for an explicitly enabled Color attribute in Style Options. It opens the matching style panel/editor after validation; inherited colors must first be enabled through the existing style command. The picker reports its bound document/revision/style under `__textStyleColor` in `ui.inspect`. Changes preview in an isolated document; OK runs the existing style `set` command once, Cancel changes nothing. Document edits/switches or closed/changed Style Options discard the picker. `textStyle` cannot be combined with `parent`, `effect`, `field` or `target`. - The shell's own dialogs (Window › Workspace › New Workspace / Delete Workspace, View › Pixel Aspect Ratio › Custom Pixel Aspect Ratio…, View › Show › Show Extras Options…, View › 32-bit Preview Options…) are listed in `ui.inspect`'s `dialogs` with the id `"shell"` (at most one is open). `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` take `{"dialog": "shell"}`; OK runs the dialog's command and keeps the dialog open if it fails - - The unsaved-changes prompt (closing a document, Revert, quitting with unsaved work) is listed in `ui.inspect`'s `dialogs` with the id `"discard"` while it is up: `fields` gives the waiting `command` (`file.close`, `file.exit`…), the `document` it asks about, how many are `remaining`, and its `choices`. `ui.dialog.confirm` takes `{"dialog": "discard", "choice": "save" | "dontSave" | "cancel"}` (default `save`; Revert takes `dontSave` or `cancel`) and answers it as the window's buttons do, one document at a time; `ui.dialog.cancel` with `{"dialog": "discard"}` cancels it. Save of an untitled document opens the save dialog first, so the reply's `fileDialog` is true and the prompt stays open until that is answered. + - The unsaved-changes prompt (closing a document, Revert, quitting with unsaved work) is listed in `ui.inspect`'s `dialogs` with the id `"discard"` while it is up: `fields` gives the waiting `command` (`file.close`, `file.exit`…), the `document` it asks about, how many are `remaining`, and its `choices`. `ui.dialog.confirm` takes `{"dialog": "discard", "choice": "save" | "saveAll" | "dontSave" | "dontSaveAll" | "cancel"}` (default `save`; Revert takes `dontSave` or `cancel`) and answers it as the window's buttons do, one document at a time. `saveAll` and `dontSaveAll` tick "Apply to All": they answer for every document still to ask about, and are listed in `choices` only while more than one is left. A document whose save is cancelled or fails is asked about again; `ui.dialog.cancel` with `{"dialog": "discard"}` cancels it. Save of an untitled document opens the save dialog first, so the reply's `fileDialog` is true and the prompt stays open until that is answered. - A save dialog's answer that PhotoCraft changes, by giving a name without an extension the suggested file's or by lowercasing the extension (Preferences › File Handling › Lowercase Extension), opens a replace prompt when a file exists under the changed name: a dialog with `__replaceSaved`, `message`, `detail` and `path` (the file the save would replace). `ui.dialog.confirm` writes the file; `ui.dialog.cancel` ends the save without writing, as Cancel in the save dialog does. The file dialog counts as open until the prompt is answered. A name that differs only in letter case and reaches the same file (Windows and macOS by default) does not open it. - Layer Style (`layerStyle {effect?}` opens on that effect kind): the fields hold the dialog's whole state, so agents read and drive it like a user. `effects` lists every effect instance in the layer's order as `{id, kind, on, params, fx}` (`fx` is the effect snapshot the dialog loaded; OK edits that snapshot with `params`, so anything the dialog doesn't model survives). `selected` picks the page (`blendingOptions` or an instance id), `preview` (default on) gates the live canvas preview, `p:blendingOptions` edits blend mode/opacity/fill opacity, and `patternList` names the usable patterns. OK replaces the layer's effects in one step (`layer.layerStyle.replace`); Cancel discards. "New Style…" saves the pending state via `style.presets.new {effects}`, a swatch click applies a style preset, and Make/Reset Default use `layer.layerStyle.makeDefault` / `layer.layerStyle.defaultFor` - Gradient Overlay exposes `params.method` (`smooth`, `perceptual`, `linear`, `classic`). `custom` denotes an existing curve without a recorded method and preserves it. Choosing a method retains all recorded source colour stops. If no source record exists (including baked PSD imports), choosing a method rebuilds from the two end colours, matching legacy command behaviour; the old curve stays unchanged until that choice. Later endpoint edits rebuild the colour curve using the recorded method. The source stops, smoothness and method survive dialog reopening, undo/redo and native `.pcraft` saves. Saving a style preset through "New Style…" may lose the multi-stop source curve: it passes only params to `style.presets.new`, and `effect_from_params` rebuilds the effect from the default gradient. PSD export continues to write the baked appearance; reopening that PSD shows Custom because editable interpolation metadata is not exported yet. Opacity interpolation and the multi-stop editor are separate work. @@ -83,10 +83,10 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`). - Image › Adjustments › Levels… (`ui.menu.invoke {id: "image.adjustments.levels"}`): `__clipping` (`"shadows"` or `"highlights"`; `null` turns it off) shows Photoshop's clipping display on the canvas instead of the preview, what the black or white Input slider clips. The app sets it while Alt and the mouse button are held on one of those sliders; it never reaches OK. The display shows only for RGB and Grayscale documents whose target is a raster layer's pixels, on the main canvas. Other targets (CMYK or Lab documents, a channel, mask or Quick Mask target, a non-pixel layer, a Smart Filter) accept the value and keep the normal preview. - Save for Web (`ui.menu.invoke {id: "file.export.saveForWebLegacy"}`) is resizable with independently scrolling settings. Dialog fields `__view` (`original|optimized|2up|4up`), `__zoom` (`null` = Fit, otherwise a factor; 1 = 100% in physical display pixels), and `__center: [u,v]` control the shared preview navigation. `__previewRects` reports pane rectangles in screen points. Drag a preview to pan, scroll/pinch to zoom at the pointer, or double-click to fit. GIF/PNG-8 expose `colorTable: ["#rrggbb", …]` (opaque source entries) and `colorTableEdits: {"0":"#rrggbb", …}` (zero-based replacements after quantization). A swatch opens a color picker; edits update the preview and saved file without remapping pixel indices or changing the document. Reset clears replacements. Changing palette/size/matte/transparency settings regenerates the table and clears index-based edits. Previews and generated tables use a bounded 2048-pixel proxy; full-size export uses that explicit table unchanged. `__paletteApproximate` reports proxy-derived palette generation, and enlarged proxy previews are labelled. The engine export command accepts the same table/edit parameters; its no-path estimate returns the source `colorTable` and `transparentIndex` as well as size statistics. Opening a new dialog does not carry a previous image's table across. Image Size has `width` and `height` (px), `percent` and `resample` (`nearest|bilinear|bicubic|bicubicSmoother|bicubicSharper`, default `bicubic`); `__constrain` (default true at each opening) links the two sides in proportion. A side edit sets both sides and removes `percent`, which the export command otherwise applies first; a Percent edit sets both sides from it. Each opening starts at the document's full size, while `resample` is remembered with the encoding choices. The document is never resized. - - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing. + - A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command only (`{"rasterized"}`; the click that opened the prompt is not replayed, as in Photoshop); `ui.dialog.cancel` does nothing. - Edit › Transform › Warp on editable type (`ui.menu.invoke {"id":"edit.transform.warp"}`, or the warp toggle of an open transform box) opens Warp mode with no prompt, as in Photoshop: the mesh can't be dragged or split, only the options bar's warp style, Bend, H and V apply, and the commit sets the layer's Warp Text in one step, so the type stays editable. Directly: `engine.execute {"command":"edit.transform.warp","params":{"style":"flag","bend":40}}` on a type layer. Distort and Perspective stay greyed for type. - `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows -- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). With the Crop tool in its default mode (Use Classic Mode off) a drag inside the box moves the image and one outside turns it, the view panning and turning with it; a drag's `move`/`up` points are read as the view showed the document at its `down`, so an `up` where the last `move` was changes nothing more. `command: true` with a painting, retouching, eraser, gradient, eyedropper or other non-selection tool makes the gesture the Move tool's, as holding ⌘ (Ctrl off the Mac) does in the app: a drag moves the active layer (the selected pixels when there is a selection), with `alt: true` as well it duplicates the layer first, and a click picks the layer under the point; the tool is unchanged afterwards. The Hand, Rotate View, Zoom, Crop, Slice, Path Selection, Pen, shape, Type and selection tools keep `command` for themselves. `ctrl: true` with `alt: true` and a brush tool is the on-canvas brush resize instead (in the app, Ctrl+Alt-drag off the Mac). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen, or with a Type tool on text being edited or on committed type, it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with Zoom or Hand (or `space: true` alone, the Hand held over any tool) it opens the view menu there (Zoom In and Zoom Out step about the pressed point; `view.fillScreen` is its Fill Screen row); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. For a painting tool's Shift+right-click, see the Mode menu exception below. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. `button` is `left` (default), `right`, `secondary` or `middle`, and an event's `kind` is `down`, `move` (default) or `up`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point. +- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], tool?, modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). With the Crop tool in its default mode (Use Classic Mode off) a drag inside the box moves the image and one outside turns it, the view panning and turning with it; a drag's `move`/`up` points are read as the view showed the document at its `down`, so an `up` where the last `move` was changes nothing more. `command: true` with a painting, retouching, eraser, gradient, eyedropper or other non-selection tool makes the gesture the Move tool's, as holding ⌘ (Ctrl off the Mac) does in the app: a drag moves the active layer (the selected pixels when there is a selection), with `alt: true` as well it duplicates the layer first, and a click picks the layer under the point; the tool is unchanged afterwards. The Hand, Rotate View, Zoom, Crop, Slice, Path Selection, Pen, shape, Type and selection tools keep `command` for themselves. `ctrl: true` with `alt: true` and a brush tool is the on-canvas brush resize instead (in the app, Ctrl+Alt-drag off the Mac). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with Marquee, Lasso, Magic Wand, Object Selection, or Pen, or with a Type tool on text being edited or on committed type, it opens a tool context menu (`canvasToolMenu` in `ui.inspect`, with ordered command ids, separators, and enabled states); with Zoom or Hand (or `space: true` alone, the Hand held over any tool) it opens the view menu there (Zoom In and Zoom Out keep the view centre with the non-temporary Zoom tool and Zoom Clicked Point to Center off; other cases retain their pressed-point behaviour; `view.fillScreen` is its Fill Screen row); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. For a painting tool's Shift+right-click, see the Mode menu exception below. The menus open at the screen position of the pressed document point. Use `ui.context.choose {id}` for enabled tool-context actions. The Pen menu is documented in `docs/context-menu-parity.md`. `button` is `left` (default), `right`, `secondary` or `middle`, and an event's `kind` is `down`, `move` (default) or `up`. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven. A `down`/`up` at the same point with the Rectangle, Ellipse, Triangle or Polygon tool opens Create Rectangle / Ellipse / Triangle / Polygon (Photoshop's click-to-size dialog); set its `width` and `height` (document pixels), `fromCenter`, `radii` [tl, tr, br, bl] (Rectangle) or `sides` and `starRatio` (percent, Polygon) with `ui.dialog.set`, then `ui.dialog.confirm` runs `shape.create` at the clicked point. - Magnetic Lasso (`tool: "magneticLasso"`): a `down`/`up` pair is a click. The first sets the first fastening point (its modifiers set the selection mode); later clicks fasten a point, or close the border on the first point. `move` events trace the border with or without a button held, fastening points by themselves; with `alt: true` a click draws a straight segment and a drag a freehand one. `ui.inspect` shows the border in progress under `magnetic` (`path`, `anchors`, `live`, `mode`). `ui.key` Enter closes it along the edges, Backspace removes the last fastening point, Escape cancels. To select along edges in one call instead, use the `select.magneticLasso` command with rough points around the shape. - Image › Adjustments › Curves on top, no eyedropper armed (#7325): a `down` with `command: true` adds a point on the curve the dialog shows (its Channel popup), at the pixel's tone (RGB: Rec. 709 luma; Gray: the mean) and at the curve's current output there, so the preview does not change; with `shift: true` as well, one point on each of Red, Green and Blue at that channel's value. It samples the merged image like the eyedroppers, never moves an existing point (a point already within 2 levels is selected instead, a 16-point curve takes no more), and the tool is not driven. Nothing is added with a pencil-drawn curve, in Lab or CMYK, or with a mask, saved channel or Quick Mask targeted. - Levels or Curves adjustment layer, Properties eyedropper armed (`layerPicker` in `ui.inspect`: `{layer, point, tool}`, set by the panel's Set Black/Neutral Gray/White Point buttons): a `down` sets that point from the image below the layer as one `layer.setAdjustment {"layer", "eyedropper": {"point", "at": [x, y], "size"}}` (send that command directly to skip the UI) and the tool is not driven; Esc, another tool or another layer disarms it. @@ -176,6 +176,7 @@ heading instead targets the whole action. Step deletion also works during record and does not undo the document edit. The control equivalent is `actions.delete {"action": "Name", "step": 0}` (zero-based). Omitting `step` deletes the whole action, which still requires recording to be stopped. +A step or action row dragged onto the trash is deleted without a confirmation, and one dragged onto the plus button is duplicated right after itself (`actions.duplicate`), as in Photoshop. Desktop actions also record and replay View › Fit on Screen (`view.fitOnScreen`), 100% (`view.actualPixels`), Zoom In and Zoom Out through their menu commands or shortcuts. @@ -565,7 +566,10 @@ Open also applies the other Camera Raw Defaults (Sharpen For as part of the Came colour space, bit depth and Open as Smart Object, so the step works on the pixels the dialog previewed; Apply auto tone fills the dialog), reported as `defaults` in the commit's reply; the resolution is set when the file opens. With "Open in Camera Raw" off the sidecar and the defaults -apply without the dialog. +apply without the dialog. A sidecar's crop (`crs:HasCrop="True"` with `CropTop` / `CropLeft` / +`CropBottom` / `CropRight`, fractions of the raw as stored, before its Orientation) crops the +document as Open re-develops it, before the Camera Raw step; the dialog previews the whole frame. +A straightened crop (`CropAngle` not 0) is named as not supported and not applied. **Opening a raw file.** An interactive open (File › Open, Open Recent, drag and drop, the command line) of a camera raw developed from its sensor data shows this dialog first, titled @@ -760,7 +764,9 @@ such as a bare layout with `dockingHidden`, loads as the default layout, built f saved `panels`, `dockTabs` and `dock`. The existing `ui.set` panel visibility, `dockTabs` selection and `dockWidth` controls -remain available after customization. Width keeps its 250–520 point clamp. Named +remain available after customization. Width requests use the window-dependent range +250..max(520, window width − 400), with achieved widths subject to column minimums +and iconic caps; constrained dock-edge rendering still reserves canvas space. Named `dock.hidden_tabs` and intact native-group collapse settings are also preserved. A legacy `dock` replacement that changes flat group order or heights is rejected after customization: use `window.panel.layout` to change a custom split tree. A replacement diff --git a/docs/development.md b/docs/development.md index d09fbfd26c..998c9b8b95 100644 --- a/docs/development.md +++ b/docs/development.md @@ -680,6 +680,25 @@ except Place, which is a job that `poll_jobs` steps on the UI thread (a *coopera ## Indexed Color timings +The stock Indexed Color dialog exposes Matte: None, Foreground Color, Background Color, +White, Black, 50% Gray, Netscape Gray and Other… (the shared Color Picker). Choosing Other… +opens the picker without replacing the current matte; Cancel leaves that choice unchanged, and +OK commits the picked `#rrggbb` in document RGB coordinates. Automation accepts `matte` as +`none`, `foreground`, `background`, `white`, `black`, `gray` (50% Gray, encoded +`#808080`), `netscapeGray` (Netscape Gray, encoded `#c0c0c0`) or `#rrggbb`. Foreground/background +tool colours are converted from the working RGB profile into the document profile and clipped +to its encodable RGB range before blending. A selected matte blends all +partially transparent edges; with Transparency on, fully clear pixels stay transparent. +With Transparency off, the selected matte also fills clear pixels. None retains the existing +hard-edged transparency/default flattening behavior. Indexed conversion retains the document's +ICC profile and encoded RGB sample representation; matte colours are interpreted in the document +RGB coordinate space. Default Indexed → RGB expands the stored RGB samples without converting +them to the working profile; an explicitly supplied destination profile still requests a CMS +conversion. Inline and worker dialog previews inherit the current foreground/background tool +colors, and changing those colors invalidates both cached frames and pending worker results, +including when the preview proxy factor changes. A same-color frame at the old factor can +remain visible during a drag until the new result arrives. This follows Adobe's documented +[Indexed Color conversion options](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-modes/conversion-options-for-indexed-color-images.html). `cargo run --release -p photocraft-engine --example indexed_color_perf -- image.png` measures palette construction, Floyd–Steinberg diffusion, and the complete full-resolution CPU preview path (proxy copy, engine command, result composition; excludes GPU upload/presentation). diff --git a/docs/feature-names.md b/docs/feature-names.md new file mode 100644 index 0000000000..e44515c0f8 --- /dev/null +++ b/docs/feature-names.md @@ -0,0 +1,17 @@ +# Feature naming + +PhotoCraft names its own raw-processing workspace **RAW Develop**, the adjustment **RAW Develop Filter**, and its raw preferences **RAW Defaults**. All 34 shipped non-English catalogs use the new keys and localized labels. + +## Compatibility boundary + +The `filter.cameraRaw` command, raw preference IDs, Rust type names and serialized settings remain stable. Existing documents retain their own saved filter names. New filters get the neutral display name. + +Adobe Camera Raw PSD/action descriptor class names, XMP namespaces and the settings-file compatibility descriptions are unchanged. Import/export mapping code and attribution are unchanged. + +A Photoshop action's step name is stored in the action file, so a saved Camera Raw step keeps Photoshop's "Camera Raw Filter" wording and a loaded action round-trips unchanged. Only PhotoCraft's own step labels, menus and windows say RAW Develop Filter. + +## Validation before readiness + +Review menu and dialog layout in the supported interfaces, run the engine/UI tests and the existing PSD/action/XMP round-trip tests, and complete the normal platform gates. This is a feature naming change, not a legal determination. + +The catalog cleanup removes 136 dormant rows for branded composer labels, PDF presets, old Photoshop defaults and the unused raw-opening label. No active non-localization call sites use those keys. Current PhotoCraft defaults and required compatibility descriptions remain intact. Regression guards cover production Rust display literals and catalog keys; explicit exceptions document interchange descriptions and identifiers. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index b3d708494d..207778cb37 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-06 · **Change:** minor (CLI `--metadata none|all` for `convert`, `run --out` and `batch`: `none` leaves the document XMP and free-form text out of flat exports, as Export As's Metadata: None, `all` the default, #9466; Hasselblad 3FR/FFF, the X2D II 100C, decodes; scripted PSD/PSB saves take `maximizeCompatibility`, and the CLI `--no-maximize-compatibility`, #8064; TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 145 supported events including Shear after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-08 · **Change:** minor (Camera Raw: an `.xmp` sidecar's crop crops the opened raw, and `crs:RawFileName` is no longer named as unsupported, #9985; CLI `--metadata none|all` for `convert`, `run --out` and `batch`: `none` leaves the document XMP and free-form text out of flat exports, as Export As's Metadata: None, `all` the default, #9466; Hasselblad 3FR/FFF, the X2D II 100C, decodes; scripted PSD/PSB saves take `maximizeCompatibility`, and the CLI `--no-maximize-compatibility`, #8064; TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 145 supported events including Shear after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 **PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`: `ScrD`/`ScrC`/`ScrL`). PSD/PSB round trips pass at 8/16/32 bits. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import. @@ -75,7 +75,7 @@ supports many more, including CR3). | Fujifilm RAF (Bayer and X-Trans) | uncompressed only; no Fuji colour calibration | | | Hasselblad 3FR/FFF | uncompressed only; compressed (lossless-JPEG) files: embedded preview only | X2D II 100C uses a measured Bayer phase; other bodies assume it with a warning (`crates/raw/src/hasselblad.rs`) | | Others (CRW, IIQ, X3F, SRW, MRW, ERF…) | embedded preview only | | -| .xmp sidecars, highlight modes, raw preferences | missing | FILE-215-11 | +| .xmp sidecars, highlight modes, raw preferences | partial (sidecars and preferences; no highlight modes) | 2026-10-28: a sidecar's crop (`crs:HasCrop` with `CropTop` / `CropLeft` / `CropBottom` / `CropRight`, fractions of the developed frame as stored, mapped through its Orientation) crops the opened raw: Open re-develops and crops before the Camera Raw step, so the post-crop vignette centres on the crop; the dialog previews the whole frame. A straightened crop (`CropAngle` not 0) isn't applied and is named, as are unreadable or empty ones; `HasCrop` missing or `False` means no crop; `RawFileName` is bookkeeping (#9985; `crates/io/src/camera_raw_xmp.rs` tests, `crates/io/tests/it/raw.rs` `camera_raw_tuning_crops_in_the_stored_orientation`, `camera_raw_ui/tests.rs` `a_sidecar_crop_crops_the_opened_raw`). 2026-10-13: sidecars fill the open-time dialog and Open writes them back; Camera Raw Defaults wired. FILE-215-11 | | Camera Raw as a PSD smart filter | partial | 2026-10-07: WB, Light/Presence, curves, HSL, grading, detail, grain, vignette mapped (FILE-215-12) | 2026-10-11: on #2135's embedded-JPEG rendering work, open-time Camera Raw tuning @@ -157,6 +157,7 @@ The original reference entry retains its source date and historical totals; curr | 2026-10-24 | minor | Hasselblad 3FR/FFF: the X2D II 100C's 16-bit uncompressed CFA decodes; compressed 3FR still opens as the embedded preview | | 2026-11-02 | minor | Actions Shear (`Shr `) loads, plays and saves the measured curve points and edge mode; unsafe subranges and unrepresentable forms remain kept steps (#10605). | | 2026-11-03 | minor | CLI `--metadata` (`none` or `all`) for `convert`, `run --out` and `batch`: `none` leaves the document's XMP packet and free-form text out of flat exports (PNG, JPEG, WebP, TIFF, …) through Export As's Metadata: None path; `all`, which keeps them as Save As does, stays the default. The ICC profile, EXIF and resolution are written as they are without the option (a palette PNG carries only its resolution, either way); PSD, PSB and `.pcraft` always keep the XMP (#9466) | +| 2026-11-03 | minor | Camera Raw `.xmp` sidecars: the crop (`crs:HasCrop` with `CropTop` / `CropLeft` / `CropBottom` / `CropRight`, fractions of the raw as stored, mapped through its Orientation) crops the opened raw, with the dialog's Open and without the dialog; out-of-range fractions are clamped, and inverted, unreadable or straightened (`CropAngle` not 0) crops are named as not supported instead of applied; PhotoCraft's own sidecar keeps the crop when it is rewritten; `crs:RawFileName` is no longer named as unsupported (#9985) | | 2026-11-01 | minor | `.atn`: 23 newer measured forms mapped, including explicit Link/Unlink, Smart Object file operations, Make Type to Shape, radius-only Shape Blur, Artboard from Group and the Crop Photos parent; supported in batch 13; Link Layers keeps the measured toggle. Artboard forms with unmeasured settings and generated Crop helper steps remain kept. | | 2026-11-01 | minor | Recorded direct Gradient Map and Lab-range Replace Color load, play and retain their measured settings on save; unsupported forms remain preserved (part of #10607). | | 2026-11-02 | minor | TIFF Options on Save As and Save a Copy (#8827): Image Compression (None, LZW, ZIP), Save Image Pyramid (half-size levels marked reduced-resolution, down to 64 px, alpha-weighted; +45 ms on a 30 MP RGB/8 save), Save Transparency (on: transparency kept ahead of alpha and spot channels, `MTrn` in a layered file; off: matted on white) and Discard Layers and Save a Copy. Scripts, `doc.save`, MCP `save` and the CLI (`--tiff-transparency`, `--tiff-pyramid`) take the same answers. JPEG compression, Pixel Order and Byte Order not offered | diff --git a/docs/gaps.md b/docs/gaps.md index 49aa80583c..5b31b6f254 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; G4: Angle/Roundness fields left of the Brush Tip Shape widget, #3825 partial; G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (G5: Warp mode edits Photoshop's Cylinder warp, #4112: the Warp menu lists it, five handles set its seven values as in the reference, and a smart object's stored cylinder opens in Warp mode as one; Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G4: Both Axes on Scatter headers, #3825 partial; G4: combined Spacing checkbox and percentage header, #3825 partial; G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; G4: Angle/Roundness fields left of the Brush Tip Shape widget, #3825 partial; G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026) Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -41,6 +41,7 @@ what an agent can't finish alone. ### G1. PSD fidelity and Photoshop acceptance - **Done 2026-10-23 (#8940):** Filter Gallery Halftone Pattern preserves size, contrast and dot/circle/line through PSD/PSB import/export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`). Malformed descriptors stay verbatim. Other unsupported gallery effects remain opaque on import or produce an export warning. +- **Average (2026-10-23):** the existing `Avrg` PSD mapping now has an executable smart-filter path. [Focused tests](average-filter.md#smart-filters) cover the command and re-rendering after discarding cached pixels; the local Photoshop RGB8 oracle is opt-in and does not change corpus floors. Broader filter parity remains open. - **Missing:** PSDs we write are not always accepted by Photoshop, and Photoshop-authored files don't always render as Photoshop renders them. - **Partial (2026-10-15, #5972 A1):** `GdFl` noise fills render when all three RGB ranges are @@ -59,7 +60,8 @@ what an agent can't finish alone. decoded whole beside the layer; layered TIFFs over the limit and huge PSBs still decode whole). No test opens our exports in a third-party editor (FILE-216-4). Mockups whose smart object uses Transform Warp's Cylinder re-rendered flat after Replace Contents (#4112, fixed 2026-10-14; - vertical cylinders and ones with perspective are still unread). + vertical cylinders and ones with perspective are still unread; Warp mode edits the cylinder + since 2026-10-27, G5). - **Impact:** PSD is the format professionals exchange. Beta requires it to be reliable. - **Estimate:** 150–250 h. **Human:** opening exports in Photoshop on the owner's Mac (or a scripted check there) is the only real oracle. @@ -269,6 +271,15 @@ what an agent can't finish alone. and 0/49% smoothing. Other presets, explicit spacing and remembered brushes retain their settings; reselect a built-in preset to take its new default. Other brush-feel and latency gaps remain open; percentages and estimates are unchanged. +- **Progress (2026-10-13, #3825 partial):** Brush Tip Shape's Spacing checkbox and + percentage share one header, removing the duplicated label. Disabled controls retain + the saved spacing; toggling does not round fractional imported values. The issue's + remaining layout and control gaps stay open. + +- **Progress (2026-10-13, #3825 partial):** Scattering and Dual Brush place Both Axes + between the Scatter label and percentage field. The existing amount track, label + scrubbing, percentage limits and disabled-section value retention are preserved. + The assessment's remaining layout and control gaps stay open. - **Progress (2026-10-13, #3825 partial):** Brush Tip Shape places Angle/Roundness controls in a left column with right-aligned labels and the interactive widget on the right. Numeric units, limits, imported values and arrow/handle interactions @@ -319,7 +330,13 @@ what an agent can't finish alone. to 100% (#2508, #2527); tool-key memory in a group (#2608, #2625); hold-a-key spring-loaded tools (#2672); H/V skew fields in the Free Transform options bar; Free Transform of several selected layers, ⌘T and the Move tool's shared frame (#6501, #3384, #6096; Warp stays one - layer). + layer); Warp mode's Cylinder + (#4112, 2026-10-27): listed in the Warp menu after the presets, outlined and cut into the + reference's 3 × 2 grid, with its five handles (two corners, the bend in the middle of the + upper arc, the lower edge in the middle of the lower arc, the wrap at the grid's centre), a + surface drag moving it, Bend, H and V greyed in the bar, and a smart object's stored cylinder + opening as one, previewed from its unwarped source (vertical cylinders + and ones in perspective stay out, as G1's PSD reader has no measurements for them). - **Detail:** [`ui-parity.md`](ui-parity.md). - **Estimate:** 60–110 h. @@ -469,6 +486,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | G5: Warp mode edits Photoshop's Cylinder warp (#4112): the Warp menu lists it after the presets, five handles set its silhouettes, edges, ellipse depths and wrap as in the reference (Bend, H and V stay greyed), and a smart object's stored cylinder opens in Warp mode as a cylinder and commits back as one; no estimate changed | | 2026-11-07 | minor | G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; compressed 3FR still opens as the embedded preview | | 2026-11-06 | minor | G12: eraser end of flipped pens on Windows (Windows Ink on) selects the Eraser (#2285); no estimate changed | | 2026-10-29 | minor | G17: web build memory handling (#10024): up-front memory checks for Place, Image Size, smart-object re-render and Save; a low-memory warning; a stopped message when the module traps; PSD save reserves its whole output; no estimate changed | @@ -504,6 +522,8 @@ what an agent can't finish alone. | 2026-10-23 | minor | G10: Amiga IFF write landed (24-plane ILBM, Save As `.iff`) and 24-plane ILBMs open | | 2026-10-23 | minor | #8940: Filter Gallery Halftone Pattern maps size, contrast and dot/circle/line both ways with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`); PSD/PSB round trips at 8/16/32 bits, malformed descriptors preserved verbatim. Other gallery effects remain partial; no floor or estimate changed. | | 2026-10-22 | minor | G11: document offsets use opening order despite tab reordering; lifecycle and `.atn` playback regressions; behavioral source evidence, no new live Photoshop reproduction | +| 2026-10-23 | minor | Average runs on Smart Objects and imported `Avrg` records; synthetic depth tests and an opt-in cold Photoshop PSD re-render are documented in [average-filter.md](average-filter.md). Corpus floors and percentages unchanged. | +| 2026-10-23 | minor | Average preserves transparency; synthetic Photoshop 26.6.1 RGB8 observations and 8/16/32-bit engine regressions in [average-filter.md](average-filter.md). Broader colour-model and feathering parity remains unmeasured; percentages and corpus floors unchanged. | | 2026-10-22 | minor | G17: Help › Check for Updates and an opt-out check once per launch (#5485), DIST-220-1 partial; estimate unchanged | | 2026-10-19 | minor | G5: Free Transform of several selected layers (#6501): one box moves them all; no estimate changed | | 2026-10-22 | minor | G1: 32-bit Hue/Saturation unclipped with Photoshop's saturation factor, bright colours keep their hue, Colorize's saturation scaled by 1 − \|Lightness\|; photoshop rgb32 hue-saturation and hue-saturation-colorize pass; Photoshop-oracle floor 188 → 190 of 258 (#5781) | @@ -563,7 +583,9 @@ what an agent can't finish alone. | 2026-10-13 | minor | G8: a Type tool click on the work path or the active shape layer's path starts type on it at the point clicked (TYPE-218-1, partial); no readiness percentage or estimate changed | | 2026-10-13 | minor | G14: lossy DNG (#5112), `.xmp` sidecars, Camera Raw Defaults wired, Calibration panel and Auto; CR3 sensor decode ruled out under the clean-room rule | | 2026-10-13 | minor | G4: Hue Jitter amount-track appearance (#3825, partial); no readiness percentage or estimate changed | +| 2026-10-13 | minor | G4: combined Spacing checkbox/percentage header (#3825, partial); disabled-value and percentage-edit behavior retained; no readiness percentage or estimate changed | | 2026-10-13 | minor | G2: Content-Aware Scale (P28) measured: carve 2013 → 556 ms, row 3.28 → 1.64 s on a 4-core VM, output unchanged; baseline, budgets and estimate unchanged | +| 2026-10-13 | minor | G4: Scattering and Dual Brush Both Axes header placement (#3825, partial); label scrubbing and value retention preserved; no readiness percentage or estimate changed | | 2026-10-13 | minor | G4: Angle/Roundness column and label alignment (#3825, partial); existing values and interactions retained; no readiness percentage or estimate changed | | 2026-10-13 | minor | G4: minimum inputs in Shape Dynamics and Transfer follow their Control (#3825, partial); no readiness percentage or estimate changed | | 2026-10-12 | minor | G5: Free Transform options bar H/V skew fields done | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 7c69231573..8b878685c7 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -2,14 +2,14 @@ Generated by `cargo xtask parity` from `crates/ui-egui/src/menu_catalog.rs` (Photoshop's menu tree) and the live command registry. Do not edit by hand. -**662 of 662 menu items live (100.0%).** +**664 of 664 menu items live (100.0%).** | Menu | Live | Total | % | |---|---:|---:|---:| -| File | 52 | 52 | 100% | +| File | 53 | 53 | 100% | | Edit | 75 | 75 | 100% | | Image | 61 | 61 | 100% | -| Layer | 162 | 162 | 100% | +| Layer | 163 | 163 | 100% | | Type | 74 | 74 | 100% | | Select | 25 | 25 | 100% | | Filter | 75 | 75 | 100% | diff --git a/docs/plugins.md b/docs/plugins.md index 4f582ae9e4..bb2859cef8 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -100,6 +100,9 @@ exports. All integers are `i32` unless noted; pointers are offsets into the modu - `name`: the menu label (1–64 printable characters). Any script works, but control characters and Unicode format characters (bidi overrides and marks, zero-width spaces, soft hyphens) are rejected, except the zero-width joiner and non-joiner, and at least one character must be visible. + Invisible padding at the ends (white space, joiners, Hangul fillers, blank Braille and other + default-ignorable blanks, and variation selectors cut off by them) is removed before these checks, + so it does not count towards the limit; marks that belong to a kept character stay. `kind`: `"filter"` (the only kind in v1). - `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, not `id`/`layer`. The host validates the user's values before calling: missing values take the default, numbers are diff --git a/docs/scorecard.md b/docs/scorecard.md index 31443c1949..cff7e384d0 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -6,12 +6,12 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | Area | Done | Partial | Missing | Key numbers | |---|---:|---:|---:|---| -| [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) | +| [Performance](#performance) | 3 | 22 | 54 | 88 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 50 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | | [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 199 (target 0) | | [Type](#type) | 5 | 5 | 0 | | -| [Automation](#automation) | 5 | 4 | 2 | 662 of 662 menu items live (100.0%) | +| [Automation](#automation) | 5 | 4 | 2 | 664 of 664 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 5 | 1 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -107,6 +107,9 @@ Baseline: 2026-10-05, 1 run, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Appl | P84 | Open a 36 MP PNG (RGB 8-bit): import (decode + tiles) (#10259) | ≤ 400 ms p95 | – | – | – | – | – | not run | [#10259](https://github.com/storytold/photocraft/issues/10259) | | P85 | Open a 36 MP PNG (RGB 16-bit): import (decode + tiles) (#10259) | ≤ 700 ms p95 | – | – | – | – | – | not run | [#10259](https://github.com/storytold/photocraft/issues/10259) | | P86 | Open a 36 MP JPEG (RGB 8-bit): import + session admission + first composite (#10259) | ≤ 500 ms p95 | – | – | – | – | – | not run | [#10259](https://github.com/storytold/photocraft/issues/10259) | +| P87 | Toggle a masked adjustment mid-stack in the layered document + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | +| P88 | Bring forward / send backward a small layer in the many-layer document + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | +| P89 | App frame after Paste Into on 24 MP (CPU canvas) | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | **Not measurable yet** (the code can't do it yet; no number is recorded): @@ -165,7 +168,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu | TOOL-213-2 | Mixer Brush tool on the toolbar | done | [#213](https://github.com/storytold/photocraft/issues/213) | Tool::MixerBrush in the Brush (B) flyout; Wet/Load/Mix/Flow/Sample All Layers options, the Current Brush Load swatch with Load Brush and Clean Brush (brush.mixer.load, brush.mixer.clean) and the automatic Load and Clean toggles; command/control dispatch and selection-clipping tests | | TOOL-213-3 | Patch tool with a live preview of the patched area | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.patch (retouch_cmds/patch.rs, source/destination) + Tool::Patch (J group: lasso, then drag the selection); the drag shows the heal live (patch_preview.rs, coarse colour fit: 1000x1000 in 52 ms) | | TOOL-213-4 | Content-Aware Move tool reusing inpaint completion | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, Structure 1-7, Color 0-10, Sample All Layers, Transform On Drop's scaleX/scaleY/rotate; background job) + Tool::ContentAwareMove (J group: lasso, then drag; Transform On Drop puts a scale/rotate box on the dropped patch, cam_transform.rs: Enter commits as one step, Esc cancels). cam_preview.rs: once the pointer or the box rests, the result shows (a cancellable background job on a smaller sampling window, #4385); a selection over 256x256 shows a coarse result solved scaled down first, then the command's exact result as a second job (#6680; 24 MP document, release: 600x400 coarse 0.26 s then exact 0.8 s, 1500x1000 0.38 s then 4.1 s, 3000x2000 0.69 s then 9.4 s; was no preview above 256x256). Tests: content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths, content_aware_move_coarse_preview_handles_transform_extend_and_limits, a_preview_within_the_full_resolution_budget_is_the_plain_solve_bit_for_bit, a_large_selection_shows_a_coarse_result_then_the_exact_one | -| TOOL-213-5 | Painting a type/shape/smart/fill layer offers to rasterize, then continues the stroke | done | [#213](https://github.com/storytold/photocraft/issues/213) | rasterize_prompt.rs: OK rasterizes then paints (two history states), Cancel does nothing; drivable via ui.dialog.confirm | +| TOOL-213-5 | Painting a type/shape/smart/fill layer offers to rasterize; OK converts it and the next click paints | done | [#213](https://github.com/storytold/photocraft/issues/213) | rasterize_prompt.rs: OK rasterizes only, the click that opened the prompt is not replayed (as in Photoshop, #8806), Cancel does nothing; drivable via ui.dialog.confirm | | TOOL-213-6 | Fill dialog: contents, blend, opacity, preserve transparency; remembered; Shift+Backspace | done | [#213](https://github.com/storytold/photocraft/issues/213) | fill_ui.rs dialog over edit.fill (fill_cmds.rs): all contents, mode, opacity, preserve; remembered in prefs; Shift+F5 / Shift+Backspace | | TOOL-213-7 | Live stroke preview for every brush-based retouch tool | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Live (canvas.rs strokes_live): Brush, Pencil, Mixer Brush, Eraser, Color Replacement, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Clone Stamp, Healing Brush, History Brush (#1026, #1040), Pattern Stamp (aligned and Impressionist) and Background Eraser (#3754); the release commits the live stroke's pixels (P32) or, for the retouch tools, the same pixels the live stroke showed (tested equal at 8 and 16 bits). Spot Healing Brush shows the area it heals as a dark overlay and heals on release, as Photoshop does. Mixer Brush uses its incremental transaction and commits the displayed result (#3627) | | TOOL-213-8 | Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Clone Source overlay drawn with opacity, inversion, circular clipping, auto-hide and the Normal/Darken/Lighten/Difference blend against the image under the brush (canvas.rs draw_clone_preview, clone_source::overlay_blend); a shaped tip (sampled bitmap, rotation, roundness) clips the overlay to its outline (brush_cursor::tip_mask, #4372); W/H link (cloneSource.set linked, panel chain button, #3298) | @@ -256,7 +259,7 @@ Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace. ## Automation -Menu wiring (`docs/parity-checklist.md`): 662 of 662 menu items live (100.0%). This counts dispatch, not behaviour. +Menu wiring (`docs/parity-checklist.md`): 664 of 664 menu items live (100.0%). This counts dispatch, not behaviour. | Id | Target | Status | Issue | Note | |---|---|---|---|---| diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1ac44f1994..16d0a79e8c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-02 · **Change:** minor (RGB and CMYK documents preview their spot inks as an overprint, FILE-215-17 narrows to PDF Separation, #10249; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; Automation Batch Esc Continue/Stop and read-only input previews now follow the measured cancellation flow; full live tabs remain partial, AUTO-219-5, #4579; Automation recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and scales point text placement; paragraph boxes remain open, #4514; Automation Batch output naming and UTF-16 logs now follow measured Photoshop behavior; progress and cancel prompt remain partial, AUTO-219-5, #4579; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; Smooth and Feather command masks cropped to selection bounds plus blur reach; Equalize with a selection asks Selected Area Only or Entire Image Based On Selected Area; cropped selection morphology and command mask conversion performance evidence added; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026; Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-02 · **Change:** minor (Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; RGB and CMYK documents preview their spot inks as an overprint, FILE-215-17 narrows to PDF Separation, #10249; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; Automation Batch Esc Continue/Stop and read-only input previews now follow the measured cancellation flow; full live tabs remain partial, AUTO-219-5, #4579; Automation recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and scales point text placement; paragraph boxes remain open, #4514; Automation Batch output naming and UTF-16 logs now follow measured Photoshop behavior; progress and cancel prompt remain partial, AUTO-219-5, #4579; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; Smooth and Feather command masks cropped to selection bounds plus blur reach; Equalize with a selection asks Selected Area Only or Entire Image Based On Selected Area; cropped selection morphology and command mask conversion performance evidence added; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026; Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -162,6 +162,11 @@ people send ×0.95 (JPEG, PNG, HEIC, WebP, PSD open; AVIF and PDF don't, #463, # ## Feature areas +Average now executes through the shared filter pipeline on Smart Objects and imported +PSD records. [Focused evidence](average-filter.md#smart-filters) covers synthetic +RGB8/16/32f cases and an opt-in Photoshop 26.6.1 RGB8 re-render after clearing caches; +this does not raise the broad filter estimate or any corpus floor. + Percent is ready-for-real-work for that area (depth and fidelity, not presence). Hours are to full parity for the area and are already contained in the dimension rows above. @@ -607,6 +612,8 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | 2026-10-25 | minor | UI / UX and Workspace rows: 12 of 178 preferences do nothing, the scorecard's count. Camera Raw row: the Calibration panel landed on 2026-10-13 (#5128); what is missing is per-camera colour for non-DNG cameras ([gaps.md](gaps.md) G14). Percentages and estimates unchanged | | 2026-10-23 | minor | Colour management and modes: PSD spot plates are stored as Photoshop stores them (ink 0 = solid), and PSDs from earlier PhotoCraft versions keep their ink (#7415 split, part 4); estimates unchanged | | 2026-10-23 | minor | Colour management and modes: spot plates now save and open in TIFF (#7415); estimates unchanged | +| 2026-10-23 | minor | Average runs on Smart Objects and imported `Avrg` records; synthetic depth tests and an opt-in cold Photoshop PSD re-render are documented in [average-filter.md](average-filter.md). Corpus floors and percentages unchanged. | +| 2026-10-23 | minor | Average preserves transparency; synthetic Photoshop 26.6.1 RGB8 observations and 8/16/32-bit engine regressions in [average-filter.md](average-filter.md). Broader colour-model and feathering parity remains unmeasured; percentages and corpus floors unchanged. | | 2026-10-22 | minor | Platforms: Help › Check for Updates and an opt-out check once per launch (#5485), DIST-220-1 partial; percentages unchanged | | 2026-10-22 | minor | Print: Japanese paper sizes (はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切) in the Print dialog, `file.print` and the PDF page, by their customary names; no percentage changed | | 2026-10-21 | minor | #8304: compound layer properties export as separate Set events, rename last; independent Photoshop replay pending; percentages and estimates unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8840897f38..aa30338e59 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (Image › Adjustments › Photo Filter… keeps Preserve Luminosity from its last OK and opens at Warming Filter (85), 25 %, as the reference application does, #9879; foreground/background swatches and exact CMYK picks restored across launches, #8485; Layer ▸ Smart Objects ▸ Reset Transform and the Layers panel row-menu item for a smart object layer: 100 % again in place with the Warp cleared and centred on the corners' average, #11662; each toolbar slot and tool key keeps its last tool across launches, #3569; Image › Adjustments › Selective Color keeps each colour's own values and applies all nine, #11463; History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (Warp mode edits Photoshop's Cylinder warp with its five handles, #4112; Hue/Saturation range zones drag, #9252; a click on the image centres a filter dialog's preview window, #9648; a gradient stop dragged off the bar is removed in every stop editor, Gradient Map and Layer Style included, #10742; Image › Adjustments › Photo Filter… keeps Preserve Luminosity from its last OK and opens at Warming Filter (85), 25 %, as the reference application does, #9879; foreground/background swatches and exact CMYK picks restored across launches, #8485; Layer ▸ Smart Objects ▸ Reset Transform and the Layers panel row-menu item for a smart object layer: 100 % again in place with the Warp cleared and centred on the corners' average, #11662; each toolbar slot and tool key keeps its last tool across launches, #3569; Image › Adjustments › Selective Color keeps each colour's own values and applies all nine, #11463; History Options snapshot options, #3634; Channels panel menu: New Channel…, Duplicate Channel, Delete Channel, New Spot Channel…, Merge Spot Channel, Channel Options…, Split Channels, Merge Channels…, #11451; a Color Picker for another dialog's colour or the Crop shield shows the picked colour there before OK, #9886; Edit › Transform › Distort side handles move their edge, Perspective side handles skew, #10085; Ctrl + Alt + wheel zooms the canvas like ⌥ + wheel on Windows and Linux, where winit reports a held Ctrl as both ctrl and command, #10488; Layers panel filter by Color, #5898; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; Shape Fill/Stroke popover as Photoshop's, every colour swatch opens the full Color Picker with a live preview; the text and gradient stop Color Pickers show the picked colour on the canvas before OK, #5530; selected colour sets edit drawing, tone and supported filters; geometry remains open; a paragraph box that can't hold its text enlarges its lower-right handle and shows a black + in it, as the reference application; Free Transform of several selected layers, #6501; Path Operations fixes: the first component keeps combining, a hidden component selection is left alone, a dragged live shape stays live, a refused Pen draft ends once; Pen, Freeform Pen, Curvature Pen and Path Selection Path Operations menu, which changes selected components, `+` / `-` keys, #1397; the Pen carries on an open shape or vector mask path; selection-aware font controls, pending caret fonts and focused commit, plus direct font-name editing with a compact no-match message, #9338; New Group dialog and button modifiers; new layers go into an open active group and join a clipping mask, except that type, shapes, pastes and placed files go above a group whose lock would refuse them; Color panel Hue and Brightness Cube show the out-of-gamut ⚠ and nearest printable colour when the field is at least 53 pt tall, #8672; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -68,6 +68,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | ⌥ scales about the reference point; ⌥-click places it; draggable reference point | done | | | ⌘-corner distort, ⌘-edge skew, ⌘⌥⇧ perspective, ⇧ rotate in 15° steps; Edit › Transform › Distort moves a side handle's edge freely (both its corners by the drag, the opposite edge fixed, stopping before the box folds), Perspective's side handles skew along their edge | done | `drag_modes.rs` (`apply_mode_drag`); Distort and Perspective side handles (#10085): `distort_mode_moves_an_edge_by_the_drag`, `distort_mode_edge_stops_before_the_box_collapses`, `distort_mode_edge_drag_commits_what_it_shows_in_one_step`, `perspective_mode_edge_slides_along_itself` | | Warp: presets, bend, split crosswise/vertical/horizontal, 3×3–5×5 and custom grids | done | | +| Warp › Cylinder: listed after the presets; outlined and cut into the reference's 3 × 2 grid; five handles (top-right and bottom-left corners, the bend in the middle of the upper arc for both arcs, the lower edge in the middle of the lower arc, the wrap handle at the grid's centre sliding right to stretch the middle) set its values, a drag on the surface moves it, and Bend, H and V stay greyed in the bar; under a placement that only scales and moves, a smart object's stored cylinder opens in Warp mode as one, previewed from its unwarped source so the picture sits on the grid, and commits back as `warpCylinder` (under a rotated, skewed, flipped or perspective placement Warp mode shows its mesh, which an untouched commit keeps and an edited one stores as a custom warp); Edit › Transform › Warp is checked while the active layer is warped | done (2026-10-27) | `transform_tool/cylinder.rs`, `warp_cmds.rs` (`smart_warp_doc_space`), `warp_mode_drags_a_cylinders_handles_and_commits_it_as_a_cylinder` (#4112). Differs: the handles were matched against the reference by a maintainer (#9798), the default wrap by observation; vertical cylinders and ones in perspective stay out, as the PSD reader has no measurements for them | | Options bar X/Y, W/H % with link, angle | done | | | With a selection, the box is the selection's rectangle and the marching ants follow the box live | done | `transform_frame`, `transform_tool.rs` (`draw_selection`): move, scale, rotate, skew, distort, perspective and warp, before the transform is applied; also the Move tool's Show Transform Controls (#5297) | | Several layers selected: one box frames them all and moves every one (pixels, type, shapes, smart objects, groups), one history step; with a selection each pixel layer's selected pixels move; Transform Again repeats on them | partial | #6501, `transform_tool.rs` (`begin_several`), `transform_several_tests.rs`, engine `edit.transform` `layers` (`transform_multi_tests.rs`); the Background is left out, as Show Transform Controls leaves it; Warp and splits are greyed for several layers; the preview moves their styles past the frame and follows opacity, fill, visibility and style edits made while the box is open (`styles_past_the_frame_move_with_the_box`, `hiding_or_fading_a_moving_layer_shows_in_the_preview_at_once`), but draws the layers stacked between the moving ones under them (the commit keeps every layer's place) | @@ -197,6 +198,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Trackpad rotate drives Rotate View | done | `rotate_view.rs:136` | | Zoom levels to 3200% and beyond | partial | #1813 | | Physical 100% at any display scale | done | #1943 | +| Filter dialogs with a preview window (Smart Sharpen, Unsharp Mask, Reduce Noise…): over the image the pointer is a small square, and a press there centres the dialog's preview on that point (clamped to the image), whatever the tool, while dragging on afterwards leaves it; a click or drag the locator starts never reaches the tool or the history, while a tool drag (a Brush stroke, a Crop frame) begun before the dialog opened still ends along its own path | done | `dialogs/filter_preview_ui.rs` `center_at`, `filter_preview_locator_tests.rs` (#9648); `ui.pointer` does the same | | ⌃Tab / ⌃⇧Tab switch document tabs | missing | #2340 | ## Selected colour channels @@ -245,6 +247,7 @@ Paragraph; the rest open as in-app floating windows. | A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools, the Move tool too; a swatch click recolours the selected type layers and shape fills whatever the tool (#9238); one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | | | A Color Picker opened for another dialog's colour (Edit › Fill's Color…, Edit › Stroke, a filter's or adjustment's colour, Replace Color's Result, New Document, New Guide and guide layout colours, channel and spot colours, Preferences) or for the Crop shield's custom colour shows the colour under the cursor there before OK, as in Photoshop, so the dialog's swatch and its own preview follow it; Cancel puts back exactly what was there, OK keeps it without a history step of its own (the dialog's OK makes the one step), and the dialog's ⌘Z history records only the picker's OK (#9886) | partial | `dialogs/color_picker_ui/live_preview.rs`, `dialogs/color_picker_ui/live_preview/tests.rs`; differs: the pickers whose OK runs a command without a preview of its own (text colour and gradient stops, open in #9757; gradient preset stops, artboard background, count group colour) and the pasteboard's custom colour show the colour only after OK | | The Type tool's Color Picker (Text Color) and a gradient fill's Color Picker (Stop Color) preview the picked colour on the canvas before OK (the selected characters, every selected type layer, or the stop); Cancel restores the document with no history step, OK commits the previewed edit in one step (#5530) | done: `dialogs/color_picker_preview.rs`, `dialogs/color_picker_preview/tests.rs` | | +| Gradient stops come off the bar: a colour or opacity stop dragged up or down off the bar is removed on release while two of its kind remain; while it is off the ramp and canvas preview show it gone, and dragging it back onto the bar cancels; the selected stop's Delete button (Remove stop, the × beside the colour, in Gradient Map) does the same. Gradient Editor, Properties, the shape gradient popover, Gradient Map and Layer Style (Gradient Overlay) share one rule (#10742) | done: `tools/gradient_ui.rs` `off_strip`, `tools/gradient_ui/editor_tests.rs`, `adjust_editors/ui_tests.rs`, `layer_style/gradient_field.rs`. Differs: Gradient Map and Layer Style show colour stops only; no Delete-key shortcut for the selected stop | | | Window size and dock width remembered | done | UI-217-2 | | Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far | | Command palette with recents | done | UI-217-7 | @@ -273,12 +276,16 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| +| 2026-11-08 | minor | Actions panel: an action or step row dragged onto the trash is deleted, and one dragged onto Create new action is duplicated right after itself (#12373) | +| 2026-10-27 | minor | Warp mode edits Photoshop's Cylinder warp (#4112): the Warp menu lists it, its five handles set its seven values as in the reference, and a smart object's stored cylinder opens as one. Scores unchanged. | | 2026-11-08 | minor | Image › Adjustments › Photo Filter… keeps Preserve Luminosity from its last OK; filter, colour and density reopen at Warming Filter (85) and 25 %, measured in the reference application (#9879); no percentage changed | +| 2026-11-07 | minor | Gradient stops dragged off the bar are removed, with a live preview and drag-back cancel, in every stop editor: Gradient Map and Layer Style gained it, the Gradient Editor, Properties and shape popover share the same threshold (#10742); row added (done); no percentage changed | | 2026-11-07 | minor | Foreground/background colours restored before the first frame (`Preferences.toolColors`, #8485), with separate pixel/mask pairs, HDR/alpha, exact CMYK ink picks and a final normal-exit flush; malformed values are ignored one by one, and first saves from older preferences merge against the default swatches so separate edits in two instances survive. No percentage changed | | 2026-11-07 | minor | Reset Transform on a smart object also clears the **Warp**, and centres on the average of the placement's four corners rather than the point its box centre maps to: measured in the reference application 2026-11-06 (a smart object warped with Arc 50, rotated 20° and scaled to 80 % came back with no warp at all, at its contents' own size, unrotated), which corrects the row below (#11662, discussion in #11675). The corner average is the box centre for an affine placement, so only Distort and Perspective placements move; the Smart Filter mask and linked masks keep following the placement, as under Free Transform. The step also requires its re-render: a visible filter PhotoCraft doesn't implement, or contents that can't be read, refuses it whole (no history state, placement and warp untouched) rather than recording the old warped pixels at the reset placement. No percentage changed | | 2026-11-06 | minor | Layer ▸ Smart Objects ▸ Reset Transform, and the same item in the Layers panel row menu for a smart object layer (#11662): 100 % of the current contents' own size again with rotation, skew, Distort and Perspective cleared and the object left centred where it is, in one undo step; the Warp and the smart filters are untouched, as Photoshop resets the transform and not the warp. No percentage changed | | 2026-11-06 | minor | Channels panel menu (☰): the channel items, not only the rows' context menu; New Channel…, New Spot Channel…, Channel Options… and Merge Channels… open their dialogs (New Channel and Merge Channels are new), and Channel Options… in Quick Mask mode opens a targeted alpha channel's options (#11451). No percentage changed | | 2026-11-05 | minor | Image › Adjustments › Selective Color keeps each colour's own Cyan, Magenta, Yellow and Black, and OK and Preview apply all nine colours; the dialog and the Properties panel share one editor (#11463) | +| 2026-11-02 | minor | Filter dialogs with a preview window: a click on the image centres the preview there, under a small square pointer, as in Photoshop (#9648). Scores unchanged. | | 2026-11-02 | minor | Edit › Transform › Distort: the side handles move their edge freely, both its corners by the drag, stopping before the box folds as a corner does; Perspective's side handles skew along their edge, as in Photoshop (#10085). Not a new command, so no percentage changed | | 2026-11-01 | minor | Every preference takes effect: 11 of 183 do nothing (was 12); Graphics Adapter always worked, but startup read it by raw JSON key, which the scorecard audit can't see | | 2026-10-31 | minor | Layers panel filter-type dropdown: Color filters by the layers' label colour (#5898); Kind, Name, Mode, Color, Smart Object and Artboard, the other three missing; no percentage changed | @@ -291,6 +298,7 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-24 | minor | Path Selection selects path components and has the Path Operations menu; the menu and `+` / `-` change the selected components' operation (`path.setOperation`); the Pen carries on an open shape layer or vector mask path from its endpoint (#1397 feedback); row stays partial until the Shape tools have the menu; no percentage changed | | 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) | | 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) | +| 2026-10-24 | minor | Hue/Saturation: dragging between a colour range's handles moves them as Photoshop 2025 does: the fully-on span moves all four, each fade its own two (#9252). Scores unchanged. | | 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips when the field is at least 53 pt tall, as the slider modes did; a click takes it (#8672). No percentage changed | | 2026-10-24 | minor | Swatches: a click recolours the selected type layers and shape fills whatever the tool, as Photoshop 2025 does (measured with the Move and Brush tools); the Color panel still recolours them only with a Type, shape or Pen tool (#9238). Scores unchanged. | | 2026-10-24 | minor | Type options bar: the alignment and paragraph-direction buttons show the edited or selected type layer's paragraph instead of the tool defaults, as Photoshop's bar does. Scores unchanged. | diff --git a/perf/budgets.toml b/perf/budgets.toml index 32d44b72d7..0d3d665e2d 100644 --- a/perf/budgets.toml +++ b/perf/budgets.toml @@ -856,3 +856,29 @@ bench = "flat_open_bench" row = "open 36 MP JPEG RGB8: editable" budget_ms = 500 enforce = false # new; no baseline yet + +# ---- #9329: redraw area of property and order changes (track only) ---------------------------- + +[[scenario]] +id = "P87" +title = "Toggle a masked adjustment mid-stack in the layered document + refresh" +issue = 9329 +bench = "perf_scenarios" +row = "toggle a masked adjustment mid-stack in the layered document + refresh" +enforce = false # new; no baseline yet + +[[scenario]] +id = "P88" +title = "Bring forward / send backward a small layer in the many-layer document + refresh" +issue = 9329 +bench = "perf_scenarios" +row = "bring forward / send backward a small layer in the many-layer document + refresh" +enforce = false # new; no baseline yet + +[[scenario]] +id = "P89" +title = "App frame after Paste Into on 24 MP (CPU canvas)" +issue = 9329 +bench = "perf_scenarios" +row = "app frame after Paste Into on 24 MP (CPU canvas)" +enforce = false # new; no baseline yet diff --git a/scorecard/tools.toml b/scorecard/tools.toml index 90f63a0f41..376f05418a 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -35,10 +35,10 @@ note = "paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, [[item]] id = "TOOL-213-5" -target = "Painting a type/shape/smart/fill layer offers to rasterize, then continues the stroke" +target = "Painting a type/shape/smart/fill layer offers to rasterize; OK converts it and the next click paints" status = "done" issue = 213 -note = "rasterize_prompt.rs: OK rasterizes then paints (two history states), Cancel does nothing; drivable via ui.dialog.confirm" +note = "rasterize_prompt.rs: OK rasterizes only, the click that opened the prompt is not replayed (as in Photoshop, #8806), Cancel does nothing; drivable via ui.dialog.confirm" [[item]] id = "TOOL-213-6"